Search code examples
c++multithreadingmutex

Is it legal to lock the std::mutex in main thread and then unlock in the child thread?


Is it legal to lock the std::mutex in main thread and then unlock in the child thread. Here is a demo snippet, which seems work.

#include <iostream>
#include <mutex>
#include <thread>
 
 int main()
 {
    std::mutex mtx;

    mtx.lock();

    std::thread([&](){mtx.unlock();}).join();

    std::thread([&](){mtx.lock();}).join();
 }


Solution

  • This is one of the patterns I use most to let threads wait for each other that does not require locks to be passed around. (This pattern is more powerful when instead of a bool you use a state enum). Otherwise you can also have a look at std::latch/std::barrier

    #include <mutex>
    #include <condition_variable>
    #include <iostream>
    
    int main()
    {
        std::mutex mtx;
        
        // despite its name a condition variable is more of an interthread signal
        // signalling something has changed that is worth checking
        std::condition_variable cv;     
    
        bool thread1_finished{ false };
    
        std::thread thread1{ [&]
        {
            std::cout << "thread 1 doing stuff\n";
            std::scoped_lock lock{mtx};
            thread1_finished = true;
            cv.notify_all();
        }};
    
        std::thread thread2{ [&]
        {
            // wait for thread 1 to finish
            {
                std::unique_lock lock{mtx};
                // this is not a busy wait.
                // thread will go to sleep until cv is signalled
                // and then it will check the predicate
                cv.wait(lock, [&] { return thread1_finished; });
            }
    
            std::cout << "thread 2 doing stuff\n";
        }};
    
        thread1.join();
        thread2.join();
        
        return 1;
    }