This is related to the second answer to this question.
My test code is below. I'm trying to launch a thread, and then to make it stop using the std::atomic_flag
. Then the thread should output a number of loop executions and total duration, and stop.
std::atomic_flag keepRunning = ATOMIC_FLAG_INIT;
void F()
{
keepRunning.test_and_set();
long long unsigned count = 0;
const time_t start = time(nullptr);
while (keepRunning.test_and_set())
{
std::cout << '.';
++count;
}
const time_t duration = time(nullptr) - start;
std::cout << count << '\t' << duration << std::endl;
}
int main()
{
std::thread t(F);
keepRunning.clear();
t.join();
}
The problem is that the thread doesn't stop.
Why is that?
- Compiler: g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
- OS: guest OS Ubuntu 14.04 on the macOS Sierra Ver 10.12.2 host
- Compilation flags - I tried
-O0
and-O4
, and it didn't make any difference.