I couldn't find much on this so I thought I'd post my own question.
I have a thread that executes a loop, locking a mutex each time. The issue is, there is not enough time between loops for another thread to lock the mutex. Here is some code that replicates my issue:
#include <thread>
#include <mutex>
#include <iostream>
#include <functional>
volatile bool bar;
void foo( std::mutex& m )
{
while( true )
{
std::unique_lock<std::mutex> lock( m );
if( bar )
break;
std::cout << "Hello World" << std::endl;
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}
}
int main( int argc, char** argv )
{
bar = false;
std::mutex m;
std::thread t( std::bind( foo, std::ref( m ) ) );
std::this_thread::sleep_for( std::chrono::seconds( 5 ) );
std::cout << "Terminating thread..." << std::endl;
{
std::unique_lock<std::mutex> lock( m );
bar = true;
}
t.join();
}
And sample output:
Hello World
Hello World
Hello World
Hello World
Hello World
Terminating thread...
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
I'm sure a simple sleep command before taking the mutex will solve my issue, but I'd like to avoid that if necessary due to the high loop rate and low latency requirements of my application.
Any ideas here? Is there a way to notify the main thread? Is std::mutex
the best choice here?
Thanks.