C++ 在线程之间传递锁

C++ 在线程之间传递锁,c++,multithreading,C++,Multithreading,如果我有一个类似下面的工作流 somelock; thread1: somelock.lock(); thread1: ... thread1: start thread2; thread1: somelock.unlock(); thread2 start : somelock.lock(); thread2:... thread2: somelock.unlock(); 条件是: 只有thread2才能在thread1解锁后获得锁定 在thre

如果我有一个类似下面的工作流

somelock;

thread1: somelock.lock();

thread1: ...

thread1: start thread2;

thread1: somelock.unlock();

      thread2 start : somelock.lock();
      thread2:...
      thread2: somelock.unlock();
条件是:

  • 只有
    thread2
    才能在
    thread1
    解锁后获得锁定

  • thread2
    unlock()之后,任何人都可以访问
    somelock
    并有机会获得锁

  • 好像锁已从
    thread1
    传递到
    thread2
    。 是用C++实现的吗?< /P> 只有thread1解锁后,thread2才能获得锁定

    您的伪代码不能保证上述条件。单独使用互斥锁是不行的。需要一种更复杂的方法:

    std::mutex mtx;
    std::condition_variable cond;
    bool thread2_done = false;
    
    void thread1()
    {
        std::unique_lock<std::mutex> guard(mtx);
    
        // do some work with mtx locked
    
        start_thread2();
    }
    
    void thread2()
    {
        std::unique_lock<std::mutex> guard(mtx);
    
        // do some work with mtx locked
    
        thread2_done = true;
        cond.notify_all();
    }
    
    void thread3()
    {
        std::unique_lock<std::mutex> guard(mtx);
        cond.wait(guard, [] { return thread2_done; });
    
        // do some work with mtx locked
    }
    
    std::mutex-mtx;
    std::条件变量cond;
    bool thread2_done=错误;
    void thread1()
    {
    标准::独特的锁紧保护装置(mtx);
    //在mtx锁定的情况下做一些工作
    开始螺纹2();
    }
    无效线程2()
    {
    标准::独特的锁紧保护装置(mtx);
    //在mtx锁定的情况下做一些工作
    thread2_done=真;
    条件通知所有人();
    }
    void thread3()
    {
    标准::独特的锁紧保护装置(mtx);
    cond.wait(保护,[{return thread2_done;});
    //在mtx锁定的情况下做一些工作
    }
    
    看起来像是家庭作业(是的,是的。:)您正在混合“工作单元”和“线程”的范例。如果您想以这种方式链接工作,那么切换线程是没有意义的。只需在当前线程中的所需点执行“thread2 work”。