Created
May 26, 2015 19:25
-
-
Save hezhao/efd6d852b624a13efec2 to your computer and use it in GitHub Desktop.
Example of shared data with multiple threads in C++
This file contains 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
#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