I have a program that computes some complicated math stuff inside a loop. I simplified it to the following:
#include <vector>
#include <thread>
#include <mutex>
struct Test
{
int threads = 4;
int threads_complete = 0;
bool idle = true;
bool stop = false;
std::mutex mtx;
// A single task
void task(int n)
{
bool done = false;
while (!stop)
{
if (idle || done) continue;
for (int i = 0; i <= 3 * (n + 1); i++)
{
printf("Task %d, iteration %d of %dn", n, i, 3 * (n + 1));
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
done = true;
// Lock thread to increment the counter
mtx.lock();
threads_complete++;
mtx.unlock();
}
}
// Launch multiple tasks
void do_tasks()
{
std::vector<std::thread> v;
// Start multiple threads
for (int i = 0; i < threads; i++)
{
v.emplace_back(&Test::task, this, i);
}
// Launch subtasks in threads
idle = false;
// Wait for all tasks to finish
while (threads_complete != threads);
// Stop all the cycles inside tasks
stop = true;
// Await for threads to quit
for (auto& t : v)
{
t.join();
}
}
};
int main()
{
Test test;
test.do_tasks();
printf("nDonen");
getchar();
}
The programs works as expected in Debug printing all the Task ...
lines and Done
in the end. However, when I run it in Release, the threads are seemed to be ignored completely and only Done
is printed in the console.