Skip to content

Instantly share code, notes, and snippets.

@coenraadhuman
Created March 11, 2019 02:55
Show Gist options
  • Save coenraadhuman/87d667a400d6243d4d35f1502edc0ed4 to your computer and use it in GitHub Desktop.
Save coenraadhuman/87d667a400d6243d4d35f1502edc0ed4 to your computer and use it in GitHub Desktop.
C++ program that simulates a race condition on a shared resource (print to stdout).
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
// mutex used to lock other threads from gaining access to shared resource
mutex m_mutex;
// shared print function for cout
void shared_print(char c, int v) {
//m_mutex.lock(); // locks other threads from using resource, uncomment to see ipc sequence complications
cout << c << v << "\n";
//m_mutex.unlock(); // unlocks resource so that another thread can have access, uncomment to see ipc sequence complications
}
// function for sequence
void foo(char d, int a) {
for (int i = 1; i <= a; i++) {
shared_print(d, i);
}
}
int main()
{
thread th2(foo, 'A', 10); // child thread - 1
thread th3(foo, 'B', 10); // child thread - 2
thread th4(foo, 'C', 10); // child thread - 3
th2.join(); // main thread, waits for child to finish
th3.join(); // main thread, waits for child to finish
th4.join(); // main thread, waits for child to finish
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment