From 8c81bbd3db5b6f4d9927a220acc5ca0e063cdf7b Mon Sep 17 00:00:00 2001 From: Tomasz Sobczyk Date: Fri, 30 Oct 2020 10:36:39 +0100 Subject: [PATCH] Fix the counter in for_each_index_with_workers going out of scope before workers finish. --- src/thread.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/thread.h b/src/thread.h index 3bc00729..1f0ec6a2 100644 --- a/src/thread.h +++ b/src/thread.h @@ -135,10 +135,15 @@ struct ThreadPool : public std::vector { typename Detail::TypeIdentity::Type end, FuncT func) { - std::atomic i_atomic = begin; + // This value must outlive the function call. + // It's fairly safe if we make it static + // because for_each_index_with_workers + // is not reentrant nor thread safe. + static std::atomic i_atomic; + i_atomic.store(begin); execute_with_workers( - [&i_atomic, end, func](Thread& th) mutable { + [end, func](Thread& th) mutable { for(;;) { const auto i = i_atomic.fetch_add(1); if (i >= end)