Skip to content

Commit 552ffe2

Browse files
authored
Add thread_setup callback to tasking::Executor (#5581)
Signed-off-by: Michał Zientkiewicz <[email protected]>
1 parent 2d6f097 commit 552ffe2

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

dali/core/exec/tasking_test.cc

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,30 @@ TEST(TaskingTest, ExecutorShutdown) {
3535
});
3636
}
3737

38+
TEST(TaskingTest, ExecutorSetup) {
39+
/** Check that setup has effect on all threads */
40+
static thread_local int tls = 0;
41+
int num_threads = 32;
42+
Executor ex(num_threads);
43+
ex.Start([]() { tls = 42; }); // set thread-local value
44+
std::atomic_int correct{0}, incorrect{0};
45+
auto complete = Task::Create([](){});
46+
int num_tasks = num_threads * 8; // launch a lot of tasks - all taks must see the expected value
47+
for (int i = 0; i < num_tasks; i++) {
48+
auto task = Task::Create([&](){
49+
if (tls == 42)
50+
++correct;
51+
else
52+
++incorrect;
53+
});
54+
complete->Succeed(task);
55+
ex.AddSilentTask(task);
56+
}
57+
ex.AddSilentTask(complete);
58+
ex.Wait(complete);
59+
EXPECT_EQ(correct, num_tasks);
60+
EXPECT_EQ(incorrect, 0);
61+
}
3862

3963
TEST(TaskingTest, IndependentTasksAreParallel) {
4064
int num_threads = 4;

include/dali/core/exec/tasking/executor.h

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#ifndef DALI_CORE_EXEC_TASKING_EXECUTOR_H_
1616
#define DALI_CORE_EXEC_TASKING_EXECUTOR_H_
1717

18+
#include <functional>
1819
#include <memory>
1920
#include <thread>
2021
#include <vector>
@@ -38,13 +39,19 @@ class Executor : public Scheduler {
3839
/** Launches the worker threads.
3940
*
4041
* Multiple calls to Start have no effect. The function is not thread safe.
42+
*
43+
* @param thread_setup A function executed before the main loop.
4144
*/
42-
void Start() {
45+
void Start(std::function<void()> thread_setup = {}) {
4346
if (started_)
4447
return;
4548
assert(workers_.empty());
4649
for (int i = 0; i < num_threads_; i++)
47-
workers_.emplace_back([this]() { RunWorker(); });
50+
workers_.emplace_back([thread_setup, this]() {
51+
if (thread_setup)
52+
thread_setup();
53+
RunWorker();
54+
});
4855
started_ = true;
4956
}
5057

0 commit comments

Comments
 (0)