Last active
January 23, 2017 02:49
-
-
Save dirtycold/8bde79c3d1e045c9a93f9805a22df24d to your computer and use it in GitHub Desktop.
test_heater with thread
This file contains hidden or 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 <iostream> | |
#include <chrono> | |
#include <thread> | |
#include <vector> | |
using namespace std; | |
bool timeout = false; | |
int main(int argc, char *argv[]) | |
{ | |
int delay = 0; | |
if (argc == 2) | |
{ | |
delay = atoi (argv [1]); | |
} | |
if (delay > 0) | |
{ | |
cout << "Will run for: " << delay << " milliseconds." << endl; | |
thread timer ([&] () { | |
this_thread::sleep_for (chrono::milliseconds (delay)); | |
timeout = true; | |
}); | |
timer.detach (); | |
} | |
else | |
{ | |
cout << "Will run forever." << endl; | |
} | |
const int n = thread::hardware_concurrency (); | |
cout << "Using " << n << " thread(s)." << endl; | |
// using vector as MSVC doesn't support variable length array | |
vector <thread> workers; | |
workers.reserve (n); | |
for (int i = 0; i < n; ++i) | |
{ | |
workers.push_back (thread ([] () { | |
// using asm to avoid using variable and volatile etc | |
// http://stackoverflow.com/questions/7083482/how-to-prevent-gcc-from-optimizing-out-a-busy-wait-loop/7084193#7084193 | |
while (! timeout) | |
{ | |
// MSVC inline assembly requires so | |
#ifdef _MSC_VER | |
__asm { nop }; | |
#else | |
asm (""); | |
#endif | |
} | |
})); | |
} | |
for (auto &worker : workers) | |
{ | |
worker.join (); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment