Skip to content

Instantly share code, notes, and snippets.

@exallium
Created March 5, 2012 03:38
Show Gist options
  • Save exallium/1976371 to your computer and use it in GitHub Desktop.
Save exallium/1976371 to your computer and use it in GitHub Desktop.
Boost Multithread Example with shared lock
#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