I am confronted to a question regarding synchronisation between threads having shared data. This is a stripped down versino of my class :

class Foo
    boost::mutex m_mutex;
    std:vector<float> m_data;
    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 );

        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 ?

  • No idea about boost. Does it have latches? Is there such a thing as putting a thread on sleep and waking it up again in C++ (thinking of Javas Object.wait() and .notify()) – marstato Sep 2 '19 at 14:52
  • Just to clarify, it looks like what you're doing is having multiple threads listen for an update and then process some data? Basically the threads are acting as consumers? – Jesse Sep 2 '19 at 15:04
  • @Jesse I'll try to clarify. Several threads are accessing internal data of this class (it's actually more than a single vector, it's several vectors). They will call this update method when they need to save all the data and then clear the vectors, that's what this update function is meant to do. When a threads is saving we want the others to pause so that they do not try to add data. – drbradock Sep 2 '19 at 15:19
  • surely it cant be good if you are allowing the other threads to modify the data during the update call? – Ewan Sep 2 '19 at 16:05
  • if you are just checking for updates then you still have a race condition. – Ewan Sep 2 '19 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.