如果我有一个像下面这样的工作流程。
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
to传递过来了thread2
。使用 C++ 可以实现吗?
只有线程 2 才能在线程 1 解锁后获取锁。
您的伪代码不保证上述条件。单独的互斥锁是行不通的。需要更复杂的方法:
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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句