Fix potential deadlock in job queue #3480
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix a bug where the Stop function's state issue may cause the Pop() function to enter an infinite loop.
template
void JobQueue::Stop() {
stop_ = true; // problem code
push_condition_.notify_all();
pop_condition_.notify_all();
}
typename JobQueue::Job JobQueue::Pop() {
std::unique_lockstd::mutex lock(mutex_);
while (jobs_.empty() && !stop_) {
push_condition_.wait(lock);
....
Bug Description:
There is a race condition between Stop() and Pop() that can lead to deadlock. The sequence is:
In Pop(), the thread evaluates while (jobs_.empty() && !stop_) and sees stop_ = false
Before entering push_condition_.wait(lock), the Stop() function gets executed:
Sets stop_ = true
Calls push_condition_.notify_all()
The Pop() thread then proceeds to push_condition_.wait(lock)
Because the notification was sent before the wait began, it's missed
Now the thread is stuck waiting indefinitely with stop_ = true, causing a deadlock