I am confronted to a question regarding synchronisation between threads having shared data. This is a stripped down versino of my class :
class Foo { private: boost::mutex m_mutex; std:vector<float> m_data; public: void update() { boost::mutex::scoped_try_lock tryLock( m_mutex ); if( false == tryLock.owns_lock() ) { // Another threads has notified that we need to update. Wait here and then return to not process the data twice. boost::mutex::scoped_lock scopedLock( m_mutex ); return; } doWork(); // will save to disk and then empty m_data } }; Some context : the update function can be called from multiple threads. If a thread has acquired the mutex I want the other threads to wait for the doWork function to finish and then return, basically to ignore the call to update(). I'm currently doing that by purposely trying to acquire a lock on a mutex that is already locked. When the thread that owns the mutex exits its update() function, it will release the mutex hence the others will acquire it and then execute the return command, thus releasing it.
My main question is : Is that good practice to try and lock a locked mutex on purpose in order to pause threads ? Or is there a better way to do it ?