Skip to content

Instantly share code, notes, and snippets.

@matutter
Created March 12, 2014 02:55
Show Gist options
  • Save matutter/9499933 to your computer and use it in GitHub Desktop.
Save matutter/9499933 to your computer and use it in GitHub Desktop.
An example demonstrating c++ threads and how mutex's work to ensure critical operation order.
// the compile args -- gcc version 4.6.3 //
// g++ this.cpp -Wall -fexceptions -std=c++0x -g -lpthread //
//////////////////////////////////////////////////////////////
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mx;
int j=0;
static void foo() {
cout << "A" << j++ << endl;
mx.lock();
for (unsigned int i = 0; i < 100000000; ++i)
{
/* code */
}
cout << "B" << j++ << endl;
cout << "FOO BAR\n";
mx.unlock();
}
int main() {
thread t(foo);
thread t2(foo);
t.join(); //note: these are unblocking function calls hence, they do the function in asynchrony
t2.join(); //the mutex.lock() allows the asynchronous threads to achieve their critical states in order of availability
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment