I have the following C++ code (greatly simplified):
void MyClass::do()
{
{
std::unique_lock<std::mutex> lock(mtx);
while (!done)
{
...
}
}
std::this_thread::yield();
}
This function is called simultaneously from multiple threads, and within those threads, it is called in a loop. What I would have expected (and what I see on ubuntu) is that when I reach the yield in one thread, if the other thread is stopped at the mutex, context switching happens and I essentially go back and forth between the two threads until one of them completes. What I see on Windows 10 is that the first thread completes (or runs the multiple iterations) before the second thread gets a chance. If I replace the yield with a sleep_for(std::chrono::milliseconds(1)), I get the results I would have expected.
It seems what is happening is that the yield does not context switch to a thread that is stopped at a mutex – even if the mutex is now unlocked.
Does any understand what is going on here and how to solve this without having to add sleeps to my code?