Ticket #5502: test.cpp

File test.cpp, 1.6 KB (added by eliothorowitz@…, 11 years ago)
Line 
1// bm.cpp
2
3// g++ test.cpp -lboost_thread-mt && ./a.out
4
5// the ration of XXX and YYY determines
6// if this works or deadlocks
7int XXX = 20;
8int YYY = 10;
9
10#include <boost/thread.hpp>
11#include <boost/thread/shared_mutex.hpp>
12
13#include <unistd.h>
14#include <iostream>
15
16using namespace std;
17
18
19
20void sleepmillis( useconds_t miliis ) {
21 usleep( miliis * 1000 );
22}
23
24void worker1( boost::shared_mutex * lk , int * x ) {
25 (*x)++; // 1
26 cout << "lock b try" << endl;
27 while ( 1 ) {
28 if ( lk->timed_lock( boost::posix_time::milliseconds( XXX ) ) )
29 break;
30 sleepmillis(YYY);
31 }
32 cout << "lock b got" << endl;
33 (*x)++; // 2
34 lk->unlock();
35}
36
37void worker2( boost::shared_mutex * lk , int * x ) {
38 cout << "lock c try" << endl;
39 lk->lock_shared();
40 (*x)++;
41 cout << "lock c got" << endl;
42 lk->unlock_shared();
43 cout << "lock c unlocked" << endl;
44 (*x)++;
45}
46
47int main() {
48
49 // create
50 boost::shared_mutex* lk = new boost::shared_mutex();
51
52 // read lock
53 cout << "lock a" << endl;
54 lk->lock_shared();
55
56 int x1 = 0;
57 boost::thread t1( boost::bind( worker1 , lk , &x1 ) );
58 while ( ! x1 );
59 assert( x1 == 1 );
60 sleepmillis( 500 );
61 assert( x1 == 1 );
62
63 int x2 = 0;
64 boost::thread t2( boost::bind( worker2, lk , &x2 ) );
65 t2.join();
66 assert( x2 == 2 );
67
68 lk->unlock_shared();
69 cout << "unlock a" << endl;
70
71 for ( int i=0; i<2000; i++ ) {
72 if ( x1 == 2 )
73 break;
74 sleepmillis(10);
75 }
76
77 assert( x1 == 2 );
78 t1.join();
79 delete lk;
80}