Skip to content

Instantly share code, notes, and snippets.

@mpkuse
Last active October 26, 2018 05:16
Show Gist options
  • Save mpkuse/7bac812c8d818e02f56d572b008f279d to your computer and use it in GitHub Desktop.
Save mpkuse/7bac812c8d818e02f56d572b008f279d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;//you can use std::lock_guard if you want to be exception safe
int i = 0;
void makeACallFromPhoneBooth()
{
//The other men wait outside
m.lock();// one man gets a hold of the phone booth door and locks it.
//man happily talks to his wife from now....
std::cout << i << " Hello Wife" << std::endl;
i++;//no other thread can access variable i until m.unlock() is called
//...until now, with no interruption from other men
m.unlock();//man unlocks the phone booth door
}
int main()
{
//This is the main crowd of people uninterested in making a phone call
//man1 leaves the crowd to go to the phone booth
std::thread man1(makeACallFromPhoneBooth);
//Although man2 appears to start second, there's a good chance he might
//reach the phone booth before man1
std::thread man2(makeACallFromPhoneBooth);
//And hey, man3 also joined the race to the booth
std::thread man3(makeACallFromPhoneBooth);
man1.join();//man1 finished his phone call and joins the crowd
man2.join();//man2 finished his phone call and joins the crowd
man3.join();//man3 finished his phone call and joins the crowd
return 0;
}
/** How having multiple threads without atomics (or locks) mess with your program.
Depending on your computer, with smaller number of threads the race condition is not
visible.
With the following program, ideally your get the output as 300000 but in reality I get
randoms.
**/
#include<iostream>
#include <vector>
#include <thread>
#include <atomic>
using namespace std;
class Fuy
{
public:
Fuy() { f=0 ; }
void inc() { f++; }
int get() { return f; }
private:
int f=0;
};
void thread_main( Fuy * obj )
{
for( int i=0 ; i<10000; i++ )
obj->inc();
}
int main()
{
Fuy * obk = new Fuy();
const int nThreads = 30 ;
vector<std::thread> th_pool;
for( int i=0 ; i<nThreads ; i++ )
{
th_pool.push_back( std::thread( thread_main, obk ) );
}
for( int i=0 ; i< th_pool.size() ; i++ )
{
th_pool[i].join();
}
cout << "Final Value : " << obk->get() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment