Created
March 12, 2014 02:55
-
-
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.
This file contains hidden or 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
// 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