我对C ++ 11的thread.h api并不了解很多(事实上,我也不熟悉线程编程,但是最近我读了很多,并了解了并发性和类似的知识),但我开始使用它,但现在遇到的问题是我从未真正遇到过。
我有两个线程函数,说这些
std::thread(thread1, args); // Spawn thread 1
std::thread(thread2, args); // Spawn thread 2
[...]
int thread1(bunch of args)
{
lock_thread_2();
[do stuff]
while (some condition) {
[do stuff]
unlock_thread_2();
}
}
int thread2(bunch of args)
{
while (some condition) {
[do stuff]
wait_for_thread1_to_unlock_me();
}
}
我最初考虑过使用std :: mutex进行操作,但是我读到它可能很危险,因为如果我解锁一个已经解锁的互斥锁,则行为是不确定的,而且在此之上它还是无法正常工作,就像Mutex.lock()不能不一定要暂停执行(只有在互斥锁已经锁定的情况下才执行),所以编写它非常可怕,我不得不将unlock()和lock()调用耦合在一起。
这里要注意的重要一点是,线程2的执行仅由线程1控制,但线程2绝不会以任何方式锁定线程1。只有线程2被线程1锁定,只有线程1控制线程2的执行流程,否则就没有控制权。
您将如何以一种干净,受支持的方式做到这一点?您愿意举一个示例代码吗?
谢谢!
std::condition_variable cv;
int thread1(bunch of args)
{
[do stuff]
while (some condition) {
[do stuff]
cv.notify_one();
}
}
int thread2(bunch of args)
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
while (some condition) {
[do stuff]
cv.wait(lk);
}
}
当wait()
返回时,要么cv
将被notify()
-ed ...或者将是一个虚假唤醒。为了处理后者,添加谓词通常会很有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句