Skip to content

Instantly share code, notes, and snippets.

@dirtycold
Last active January 23, 2017 02:49
Show Gist options
  • Save dirtycold/8bde79c3d1e045c9a93f9805a22df24d to your computer and use it in GitHub Desktop.
Save dirtycold/8bde79c3d1e045c9a93f9805a22df24d to your computer and use it in GitHub Desktop.
test_heater with thread
#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