Reputation: 1997
If I have the a workflow like the one below.
somelock;
thread1: somelock.lock();
thread1: ...
thread1: start thread2;
thread1: somelock.unlock();
thread2 start : somelock.lock();
thread2:...
thread2: somelock.unlock();
With the condition that:
only thread2
can acquire the lock after thread1
unlock.
after thread2
unlock(), any one have access to somelock
have a chance to acquire the lock.
As if the lock has been pass from thread1
to thread2
.
Is it achievable using C++?
Upvotes: 0
Views: 1006
Reputation: 1519
only thread2 can acquire the lock after thread1 unlock.
Your pseudo-code doesn't guarantee the above condition. A mutex alone won't do the trick. A more complex approach is required:
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
}
Upvotes: 1