File tree Expand file tree Collapse file tree 2 files changed +23
-4
lines changed
library/cpp/threading/local_executor Expand file tree Collapse file tree 2 files changed +23
-4
lines changed Original file line number Diff line number Diff line change @@ -14,9 +14,21 @@ int NPar::TTbbLocalExecutor<RespectTls>::GetThreadCount() const noexcept {
14
14
15
15
template <bool RespectTls>
16
16
int NPar::TTbbLocalExecutor<RespectTls>::GetWorkerThreadId() const noexcept {
17
- return TbbArena.execute ([] {
18
- return tbb::this_task_arena::current_thread_index ();
19
- });
17
+ static thread_local int WorkerThreadId = -1 ;
18
+ if (WorkerThreadId == -1 ) {
19
+ // Can't rely on return value except checking that it is 'not_initialized' because of
20
+ // "Since a thread may exit the arena at any time if it does not execute a task, the index of
21
+ // a thread may change between any two tasks"
22
+ // (https://oneapi-spec.uxlfoundation.org/specifications/oneapi/latest/elements/onetbb/source/task_scheduler/task_arena/this_task_arena_ns#_CPPv4N3tbb15this_task_arena20current_thread_indexEv)
23
+ const auto tbbThreadIndex = tbb::this_task_arena::current_thread_index ();
24
+ if (tbbThreadIndex == tbb::task_arena::not_initialized) {
25
+ // This thread does not belong to TBB worker threads
26
+ WorkerThreadId = 0 ;
27
+ } else {
28
+ WorkerThreadId = ++RegisteredThreadCounter;
29
+ }
30
+ }
31
+ return WorkerThreadId;
20
32
}
21
33
22
34
template <bool RespectTls>
Original file line number Diff line number Diff line change 9
9
#include < contrib/libs/tbb/include/tbb/task_arena.h>
10
10
#include < contrib/libs/tbb/include/tbb/task_group.h>
11
11
12
+ #include < atomic>
13
+
14
+
12
15
namespace NPar {
13
16
template <bool RespectTls = false >
14
17
class TTbbLocalExecutor final : public ILocalExecutor {
15
18
public:
16
19
TTbbLocalExecutor (int nThreads)
17
20
: ILocalExecutor()
18
21
, TbbArena(nThreads)
19
- , NumberOfTbbThreads(nThreads) {}
22
+ , NumberOfTbbThreads(nThreads)
23
+ , RegisteredThreadCounter(0 )
24
+ {}
20
25
~TTbbLocalExecutor () noexcept override {}
21
26
22
27
virtual int GetWorkerThreadId () const noexcept override ;
@@ -44,5 +49,7 @@ namespace NPar {
44
49
mutable tbb::task_arena TbbArena;
45
50
tbb::task_group Group;
46
51
int NumberOfTbbThreads;
52
+
53
+ mutable std::atomic_int RegisteredThreadCounter;
47
54
};
48
55
}
You can’t perform that action at this time.
0 commit comments