Last active
April 1, 2018 16:40
-
-
Save kassane/da81a476d7dd11722fc0f590e9b20ae6 to your computer and use it in GitHub Desktop.
Multithread C++ Modern
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
/* | |
***************************************************************** | |
* THREADING - CHAPTER 1 | |
***************************************************************** | |
*/ | |
#include <chrono> | |
#include <iostream> | |
#include <memory> | |
#include <mutex> | |
#include <random> | |
#include <thread> | |
#include <vector> | |
using namespace std; | |
mutex mtx, mvalue; | |
vector<int> values; | |
int randomValue(const int min, const int max) { | |
static thread_local mt19937 generator( | |
hash<thread::id>()(this_thread::get_id())); | |
uniform_int_distribution<int> dist(min, max); | |
return dist(generator); | |
} | |
void threadfunc(int tid) { | |
mtx.lock(); | |
auto start = chrono::system_clock::now(); | |
cout << "Starting thread: " << tid << endl; | |
mtx.unlock(); | |
mvalue.lock(); | |
int val = values[0]; | |
mvalue.unlock(); | |
int rval = randomValue(0, 10); | |
val += rval; | |
mtx.lock(); | |
cout << "Thread " << tid << " adding " << rval << ". New value: " << val | |
<< endl; | |
mtx.unlock(); | |
mvalue.lock(); | |
values.push_back(val); | |
mvalue.unlock(); | |
mtx.lock(); | |
chrono::duration<double> dur = chrono::system_clock::now() - start; | |
cout << "\nThread[" << tid << "] time: " << dur.count() << "ms \n\n"; | |
mtx.unlock(); | |
} | |
int main() { | |
auto start = chrono::system_clock::now(); | |
values.push_back(42); | |
cout << endl; | |
vector<thread> vt; | |
int n=1; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); | |
n++; | |
vt.emplace_back(thread(threadfunc, n)); //n == 9 | |
cout << endl; | |
for (auto& i : vt) { | |
i.join(); | |
} | |
cout << "Input: " << values[0] << ", Result 1: " << values[1] | |
<< ", Result 2: " << values[2] << ", Result 3: " << values[3] << endl; | |
chrono::duration<long double> dur = chrono::system_clock::now() - start; | |
cout << "\nTotal time: " << dur.count() << "ms \n\n"; | |
// return cin.get(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example based in ebook ("Mastering Multithreading C++")