Skip to content

Instantly share code, notes, and snippets.

@hezhao
Created May 26, 2015 19:25
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 hezhao/efd6d852b624a13efec2 to your computer and use it in GitHub Desktop.
Save hezhao/efd6d852b624a13efec2 to your computer and use it in GitHub Desktop.
Example of shared data with multiple threads in C++
#include <atomic>
#include <conio.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
atomic<int> data(0);
void calc()
{
while (true) {
this_thread::sleep_for(chrono::milliseconds(1));
data++;
}
}
void print()
{
while (true) {
this_thread::sleep_for(chrono::milliseconds(100));
cout << "data = " << data << endl;
}
}
int main()
{
thread t1(calc);
thread t2(print);
t1.join();
t2.join();
_getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment