diff options
author | Han-Lin Chen <hanlinchen@chromium.org> | 2024-10-29 08:57:55 +0000 |
---|---|---|
committer | Kieran Bingham <kieran.bingham@ideasonboard.com> | 2024-11-28 17:50:55 +0000 |
commit | 4d9db06d669044c0c461a2aed79c85c7fe32a502 (patch) | |
tree | ef4ef979b3146962a632bc44eef43de43444cc32 /src | |
parent | d711a4c015e74c7a77cfeba17b621909385f4494 (diff) |
libcamera: add method to set thread affinity
Add method to set thread affinity to Thread class.
Signed-off-by: Han-Lin Chen <hanlinchen@chromium.org>
Co-developed-by: Harvey Yang <chenghaoyang@chromium.org>
Signed-off-by: Harvey Yang <chenghaoyang@chromium.org>
Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Signed-off-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Diffstat (limited to 'src')
-rw-r--r-- | src/libcamera/base/thread.cpp | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/libcamera/base/thread.cpp b/src/libcamera/base/thread.cpp index 8735670b..f6322fe3 100644 --- a/src/libcamera/base/thread.cpp +++ b/src/libcamera/base/thread.cpp @@ -9,6 +9,7 @@ #include <atomic> #include <list> +#include <optional> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> @@ -128,6 +129,8 @@ private: int exitCode_; MessageQueue messages_; + + std::optional<cpu_set_t> cpuset_; }; /** @@ -281,6 +284,8 @@ void Thread::startThread() data_->tid_ = syscall(SYS_gettid); currentThreadData = data_; + setThreadAffinityInternal(); + run(); } @@ -411,6 +416,48 @@ bool Thread::wait(utils::duration duration) } /** + * \brief Set the CPU affinity mask of the thread + * \param[in] cpus The list of CPU indices that the thread is set affinity to + * + * The CPU indices should be within [0, std::thread::hardware_concurrency()). + * If any index is invalid, this function won't modify the thread affinity and + * will return an error. + * + * \return 0 if all indices are valid, -EINVAL otherwise + */ +int Thread::setThreadAffinity(const Span<const unsigned int> &cpus) +{ + const unsigned int numCpus = std::thread::hardware_concurrency(); + + MutexLocker locker(data_->mutex_); + data_->cpuset_ = cpu_set_t(); + CPU_ZERO(&data_->cpuset_.value()); + + for (const unsigned int &cpu : cpus) { + if (cpu >= numCpus) { + LOG(Thread, Error) << "Invalid CPU " << cpu << "for thread affinity"; + return -EINVAL; + } + + CPU_SET(cpu, &data_->cpuset_.value()); + } + + if (data_->running_) + setThreadAffinityInternal(); + + return 0; +} + +void Thread::setThreadAffinityInternal() +{ + if (!data_->cpuset_) + return; + + const cpu_set_t &cpuset = data_->cpuset_.value(); + pthread_setaffinity_np(thread_.native_handle(), sizeof(cpuset), &cpuset); +} + +/** * \brief Check if the thread is running * * A Thread instance is considered as running once the underlying thread has |