Thread: Fix setThreadAffinity race condition in start

Previously we call Thread::setThreadAffinityInternal in
Thread::startThread. The purpose was to avoid the main workload being
run on incorrect CPUs. This leads to a race condition of setting
`Thread::thread_` in `Thread::start()` and accessing
`Thread::setThreadAffinityInternal` though.

This patch moves the call after the construction of std::thread to avoid
the race condition. The downside is that the first tasks, if any, upon
starting a thread might be run on incorrect CPUs.

Fixes: 4d9db06d66 ("libcamera: add method to set thread affinity")
Signed-off-by: Harvey Yang <chenghaoyang@chromium.org>
Reviewed-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
This commit is contained in:
Harvey Yang 2025-01-07 14:41:37 +00:00 committed by Laurent Pinchart
parent 8d50577c0f
commit d49a84a4f3

View file

@ -257,6 +257,8 @@ void Thread::start()
data_->exit_.store(false, std::memory_order_relaxed); data_->exit_.store(false, std::memory_order_relaxed);
thread_ = std::thread(&Thread::startThread, this); thread_ = std::thread(&Thread::startThread, this);
setThreadAffinityInternal();
} }
void Thread::startThread() void Thread::startThread()
@ -284,8 +286,6 @@ void Thread::startThread()
data_->tid_ = syscall(SYS_gettid); data_->tid_ = syscall(SYS_gettid);
currentThreadData = data_; currentThreadData = data_;
setThreadAffinityInternal();
run(); run();
} }