Created
March 5, 2012 03:38
-
-
Save exallium/1976371 to your computer and use it in GitHub Desktop.
Boost Multithread Example with shared lock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/thread.hpp> | |
using namespace std; | |
using boost::thread; | |
using boost::mutex; | |
using boost::shared_lock; | |
using boost::shared_mutex; | |
using boost::upgrade_lock; | |
using boost::upgrade_to_unique_lock; | |
mutex a; | |
shared_mutex b; | |
const int THREAD_COUNT = 10; | |
void worker(int i) { | |
a.lock(); | |
cout << "Worker thread " << i << endl; | |
a.unlock(); | |
shared_lock<shared_mutex> lock(b); | |
a.lock(); | |
cout << "Worker thread " << i << endl; | |
a.unlock(); | |
} | |
int main(int argc, char** argv) | |
{ | |
thread *threads[THREAD_COUNT]; | |
upgrade_lock<shared_mutex> lock(b); | |
upgrade_to_unique_lock<shared_mutex> uniqueLock(lock); | |
// Creation | |
for(int i = 0; i < THREAD_COUNT; i++) { | |
threads[i] = new thread(worker, i); | |
} | |
cin.get(); | |
cout << "Unlocking..." << endl; | |
uniqueLock.~upgrade_to_unique_lock(); | |
// Cleanup | |
for(int i = 0; i < THREAD_COUNT; i++) { | |
threads[i]->join(); | |
delete threads[i]; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment