forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.cpp
More file actions
53 lines (40 loc) · 1.08 KB
/
Copy paththreads.cpp
File metadata and controls
53 lines (40 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<thread>
#include<mutex>
// compile with:
// g++ --std=c++14 -pedantic -Wall -pthread threads.cpp
using namespace std;
mutex writeMutex;
// This function counts to 10 with a small random delay between counts
// The tabs argument lets us differentiate between different
// threads visually.
void count_to_ten(int tabs) {
int delay;
for(int jj=0;jj<10;jj++) {
delay = ((tabs % 4) * 100) + (rand() % 1000);
this_thread::sleep_for(chrono::milliseconds(delay));
// The next line locks the output stream so the threads
// write over each other.
unique_lock<mutex> lock(writeMutex);
for(int ii=0;ii<tabs;ii++) {
cout << "\t";
}
cout << jj << endl;
}
}
int main() {
constexpr int numThreads = 6;
std::thread t[numThreads];
srand(time(NULL));
// count_to_ten(3);
// Create the threads
for(int ii=0;ii<numThreads;ii++) {
t[ii] = thread(count_to_ten, ii);
}
// Wait for each thread to complete
for(int ii=0;ii<numThreads;ii++) {
t[ii].join();
}
cout << "FINISHED" << endl;
return 0;
}