Skip to content

Instantly share code, notes, and snippets.

@erh
Created April 25, 2011 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erh/940746 to your computer and use it in GitHub Desktop.
Save erh/940746 to your computer and use it in GitHub Desktop.
boost shared_mutex test
// bm.cpp
// g++ test.cpp -lboost_thread-mt && ./a.out
// the ration of XXX and YYY determines
// if this works or deadlocks
int XXX = 20;
int YYY = 10;
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <unistd.h>
#include <iostream>
using namespace std;
void sleepmillis( useconds_t miliis ) {
usleep( miliis * 1000 );
}
void worker1( boost::shared_mutex * lk , int * x ) {
(*x)++; // 1
cout << "lock b try" << endl;
while ( 1 ) {
if ( lk->timed_lock( boost::posix_time::milliseconds( XXX ) ) )
break;
sleepmillis(YYY);
}
cout << "lock b got" << endl;
(*x)++; // 2
lk->unlock();
}
void worker2( boost::shared_mutex * lk , int * x ) {
cout << "lock c try" << endl;
lk->lock_shared();
(*x)++;
cout << "lock c got" << endl;
lk->unlock_shared();
cout << "lock c unlocked" << endl;
(*x)++;
}
int main() {
// create
boost::shared_mutex* lk = new boost::shared_mutex();
// read lock
cout << "lock a" << endl;
lk->lock_shared();
int x1 = 0;
boost::thread t1( boost::bind( worker1 , lk , &x1 ) );
while ( ! x1 );
assert( x1 == 1 );
sleepmillis( 500 );
assert( x1 == 1 );
int x2 = 0;
boost::thread t2( boost::bind( worker2, lk , &x2 ) );
t2.join();
assert( x2 == 2 );
lk->unlock_shared();
cout << "unlock a" << endl;
for ( int i=0; i<2000; i++ ) {
if ( x1 == 2 )
break;
sleepmillis(10);
}
assert( x1 == 2 );
t1.join();
delete lk;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment