isocpp / isocpp/CppCoreGuidelines
CP.42: Don’t wait without a condition
@cubbimew is already working on this.
Since Sep 3, 2020.
- Dominant language
- CSS
- Stars
- 45.3k
- Forks
- 5.6k
- PR merge metrics
- No merged PRs in 30d
Description
More specific than #554 so I figured I'd open a new issue.
"CP.42: Don’t wait without a condition" gives this "example, bad":
void thread1() {
while (true) {
// do some work ... [for the sake of argument let's say q.push(42)]
std::unique_lock<std::mutex> lock(mx);
cv.notify_one(); // wake other thread
}
}
void thread2() {
while (true) {
std::unique_lock<std::mutex> lock(mx);
cv.wait(lock); // might block forever
// do work ... [for the sake of argument let's say q.pop()]
}
}
Here, if some other thread consumes thread1’s notification, thread2 can wait forever.
That's true, but adding a condition to the wait doesn't actually fix that problem. If the cv.notify_one() can be consumed by "some other thread," then there's really nothing thread2 will ever be able to do about that.
void thread2() {
while (true) {
std::unique_lock<std::mutex> lock(mx);
cv.wait(lock, [](){ return !q.empty(); }); // STILL might block forever
// do work ... [for the sake of argument let's say q.pop()]
}
}
I think the original "example, bad" needs to be a complete example; i.e., replace the "do work..." comments with actual code that can be evaluated by the reader. I don't know if it's possible to create an example where
cv.wait(lock, some_condition)is correct,cv.wait(lock)is buggy, andcv.wait(lock)isn't just obviously wrong and out of step with the programmer's intent.
Or, maybe the appropriate solution is to replace the words "if some other thread consumes thread1’s notification" with the words "if thread1's notification arrives before thread2 has begun waiting on cv"?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.