Skip to content

Instantly share code, notes, and snippets.

Created February 14, 2014 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4f3f1bbcd7fe565b7876 to your computer and use it in GitHub Desktop.
Save anonymous/4f3f1bbcd7fe565b7876 to your computer and use it in GitHub Desktop.
Fair implementation of boost::upgrade_lock using an external mutex.
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
using namespace boost;
mutex outLock;
shared_mutex workerAccess;
bool shouldIWork = true;
mutex upgrade_fairness_lock;
class WorkerKiller
{
public:
void operator()()
{
upgrade_lock<shared_mutex> lock(workerAccess);
std::cout << "I've got the upgrade_lock!" << std::endl;
upgrade_fairness_lock.lock();
upgrade_to_unique_lock<shared_mutex> uniqueLock(lock);
upgrade_fairness_lock.unlock();
cout << "Grabbed exclusive lock, killing system" << endl;
sleep(2);
shouldIWork = false;
cout << "KILLING ALL WORK" << endl;
}
private:
};
class Worker
{
public:
Worker()
{
}
void operator()()
{
upgrade_fairness_lock.lock();
shared_lock<shared_mutex> lock(workerAccess);
upgrade_fairness_lock.unlock();
if (!shouldIWork) {
outLock.lock();
cout << "Workers are on strike. This worker refuses to work" << endl;
outLock.unlock();
} else {
sleep(1);
outLock.lock();
cout << "Worked finished her work" << endl;
outLock.unlock();
}
}
};
int main(int argc, char* argv[])
{
Worker w1;
Worker w2;
Worker w3;
Worker w4;
WorkerKiller wk;
boost::thread workerThread1(w1);
boost::thread workerThread2(w2);
for ( int i = 0; i < 20; i++ )
{
usleep(500000);
Worker w;
boost::thread workerThread(w);
}
boost::thread workerKillerThread(wk);
for ( int i = 0; i < 415; i++ )
{
usleep(500000);
Worker w;
boost::thread workerThread(w);
}
boost::thread workerThread3(w3);
boost::thread workerThread4(w4);
workerThread1.join();
workerThread2.join();
workerKillerThread.join();
workerThread3.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment