By running TSAN on the ThreadPool unit tests it was discovered that the
threads in the pool can pop tasks off the queue at the same time the
"wait" routine is trying to check if the task queue is empty. This patch
fixes this problem by checking for active threads in the waiter before
checking whether the queue is empty.
Patch by Jason Henline.
Differential Revision: http://reviews.llvm.org/D18811
Reviewers: joker.eph, jlebar
llvm-svn: 265618
void ThreadPool::wait() {
// Wait for all threads to complete and the queue to be empty
std::unique_lock<std::mutex> LockGuard(CompletionLock);
+ // The order of the checks for ActiveThreads and Tasks.empty() matters because
+ // any active threads might be modifying the Tasks queue, and this would be a
+ // race.
CompletionCondition.wait(LockGuard,
- [&] { return Tasks.empty() && !ActiveThreads; });
+ [&] { return !ActiveThreads && Tasks.empty(); });
}
std::shared_future<ThreadPool::VoidTy> ThreadPool::asyncImpl(TaskTy Task) {