This code demonstrates that the mutex is being shared between two threads, but something weird is going on with the scoping block around thread_mutex
.
(I have a variation of this code in another question, but this seems like a second mystery.)
#include <thread>
#include <mutex>
#include <iostream>
#include <unistd.h>
int main ()
{
std::mutex m;
std::thread t ([&] ()
{
while (true)
{
{
std::lock_guard <std::mutex> thread_lock (m);
usleep (10*1000); // or whatever
}
std::cerr << "#";
std::cerr.flush ();
}
});
while (true)
{
std::lock_guard <std::mutex> main_lock (m);
std::cerr << ".";
std::cerr.flush ();
}
}
This basically works, as it is, but the scoping block around thread_lock
should theoretically not be necessary. However, if you comment it out...
#include <thread>
#include <mutex>
#include <iostream>
#include <unistd.h>
int main ()
{
std::mutex m;
std::thread t ([&] ()
{
while (true)
{
// {
std::lock_guard <std::mutex> thread_lock (m);
usleep (10*1000); // or whatever
// }
std::cerr << "#";
std::cerr.flush ();
}
});
while (true)
{
std::lock_guard <std::mutex> main_lock (m);
std::cerr << ".";
std::cerr.flush ();
}
}
The output is like this:
........########################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
i.e., it seems like the thread_lock
NEVER yields to main_lock
.
Why does thread_lock
always gain the lock and main_lock
always wait, if the redundant scoping block is removed?