为什么 std::condition_variable wait() 需要 std::unique_lock arg?
我的线程不需要被锁定。 std::unique_lock
在构造时锁定线程。我只是使用 cond_var.wait() 作为避免繁忙等待的方法。我基本上通过将 unique_lock 放在一个很小的范围内来规避自动锁定,从而在它离开这个小范围后销毁唯一锁。此外,如果相关的话,只有一个消费者线程。
{
std::unique_lock<std::mutex> dispatch_ul(dispatch_mtx);
pq_cond.wait(dispatch_ul);
}
是否有更好的选择来避免 unique_lock 不必要的自动锁定功能?我正在寻找一个无互斥选项来简单地向线程发出信号,我知道 std:: condition_variable_any 但这需要某种互斥体,这在我的情况下又是不必要的。
My thread does not need to be locked. std::unique_lock
locks thread on construction. I am simply using cond_var.wait()
as a way to avoid busy waiting. I have essentially circumvented the auto-locking by putting the unique_lock within a tiny scope and hence destroying the unique lock after it leaves the tiny scope. Additionally, there is only a single consumer thread if that's relevant.
{
std::unique_lock<std::mutex> dispatch_ul(dispatch_mtx);
pq_cond.wait(dispatch_ul);
}
Is there possibly a better option to avoid the unnecessary auto-lock functionality from the unique_lock? I'm looking for a mutexless option to simply signal the thread, I am aware of std::condition_variable_any but that requires a mutex of sorts which is yet again unnessesary in my case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你需要一个锁来防止这种常见的新手错误:
同时:
条件变量不是标志。它不记得它已被通知。如果生产者在消费者进入
wait()
调用之前调用notify_one()
或notify_all()
,那么通知就“丢失”了。为了防止丢失通知,必须有一些共享数据告诉消费者是否需要等待,并且必须有一个锁来保护共享数据。
生产者应该:
消费者必须:
消费者需要将锁传递给
wait(...)
调用,以便wait(...)
可以暂时解锁它,然后重新锁定它返回之前。如果wait(...)
没有解锁锁,那么生产者将永远无法到达notify()
调用。You need a lock to prevent this common newbie mistake:
some_condition.notify_all()
,meanwhile:
some_condition.wait(...)
A condition variable is not a flag. It does not remember that it was notified. If the producer calls
notify_one()
ornotify_all()
before the consumer has entered thewait()
call, then the notification is "lost."In order to prevent lost notifications, there must be some shared data that tells the consumer whether or not it needs to wait, and there must be a lock to protect the shared data.
The producer should:
The consumer must then:
The consumer needs to pass the lock in to the
wait(...)
call so thatwait(...)
can temporarily unlock it, and then re-lock it before returning. Ifwait(...)
did not unlock the lock, then the producer would never be able to reach thenotify()
call.