1 #include <boost/config.hpp>
3 #if defined(BOOST_MSVC)
4 #pragma warning(disable: 4786) // identifier truncated in debug info
5 #pragma warning(disable: 4710) // function not inlined
6 #pragma warning(disable: 4711) // function selected for automatic inline expansion
7 #pragma warning(disable: 4514) // unreferenced inline removed
10 // weak_ptr_mt_test.cpp
12 // Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
13 // Copyright 2005, 2008 Peter Dimov
15 // Distributed under the Boost Software License, Version 1.0.
16 // See accompanying file LICENSE_1_0.txt or copy at
17 // http://www.boost.org/LICENSE_1_0.txt
19 #include <boost/shared_ptr.hpp>
20 #include <boost/weak_ptr.hpp>
21 #include <boost/bind.hpp>
29 #include <boost/detail/lightweight_thread.hpp>
34 int const k = 512; // vector size
35 int const m = 16; // threads
37 void test( std::vector< boost::shared_ptr<int> > & v )
39 using namespace std; // printf, rand
41 std::vector< boost::weak_ptr<int> > w( v.begin(), v.end() );
43 int s = 0, f = 0, r = 0;
45 for( int i = 0; i < n; ++i )
47 // randomly kill a pointer
49 v[ rand() % k ].reset();
52 for( int j = 0; j < k; ++j )
54 if( boost::shared_ptr<int> px = w[ j ].lock() )
63 // rebind anyway with prob. 50% for add_ref_lock() against weak_release() contention
71 w[ j ] = v[ rand() % k ];
75 printf( "\n%d locks, %d forced rebinds, %d normal rebinds.", s, f, r );
78 #if defined( BOOST_HAS_PTHREADS )
80 char const * thmodel = "POSIX";
84 char const * thmodel = "Windows";
90 using namespace std; // printf, clock_t, clock
92 printf("Using %s threads: %d threads, %d * %d iterations: ", thmodel, m, n, k );
94 std::vector< boost::shared_ptr<int> > v( k );
96 for( int i = 0; i < k; ++i )
98 v[ i ].reset( new int( 0 ) );
105 for( int i = 0; i < m; ++i )
107 boost::detail::lw_thread_create( a[ i ], boost::bind( test, v ) );
110 v.resize( 0 ); // kill original copies
112 for( int j = 0; j < m; ++j )
114 pthread_join( a[j], 0 );
119 printf("\n\n%.3f seconds.\n", static_cast<double>(t) / CLOCKS_PER_SEC);