使用 spdlog 以异步模式记录日志时,如何为 spdlog 使用的线程设置 cpu 亲和力?

问题描述 投票:0回答:2

我正在使用 spdlog 以异步模式进行日志记录。我想将日志记录任务分配给一个CPU核心。 spdlog 中是否有 API 可以实现此目的?

cpu-usage spdlog
2个回答
1
投票

目前,我有一个解决方法可以在库文件 threadpool-inl.h 中创建线程池时设置关联性

SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start)
    : q_(q_max_items)
{
    //printf("number of threads %lu", threads_n);
    if (threads_n == 0 || threads_n > 1000)
    {
        throw_spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
                        "range is 1-1000)");
    }
    for (size_t i = 0; i < threads_n; i++)
    {
        threads_.emplace_back([this, on_thread_start] {
            on_thread_start();
            this->thread_pool::worker_loop_();
        });
        // Create a cpu_set_t object representing a set of CPUs. Clear it and mark only CPU 2 as set.
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(2, &cpuset);
        int rc = pthread_setaffinity_np(threads_[i].native_handle(), sizeof(cpu_set_t), &cpuset);
        if (rc != 0) {
            printf( "Error calling pthread_setaffinity_np: %d \n", rc);
        }
    }
}

0
投票

我找到了一个不需要修改库源代码的解决方案。

只需创建一个自定义线程池并定义

on_thread_start
回调函数,该函数将在工作线程开始运行之前、工作线程创建之后调用。

示例代码:

void set_cpu_affinity(int cpu_id ) {
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(cpu_id, &cpuset);
    int result = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
    if (result != 0) {
        std::cerr << "Error setting CPU affinity: " << result << std::endl;
    } else {
        std::cout << "Set affinity to CPU " << cpu_id << std::endl;
    }
}

int main() {
  
  constexpr int num_items   = 8192;
  constexpr int num_threads = 1;
  constexpr int target_core = 2;

  auto on_thread_start = [target_core ]() {
     set_cpu_affinity(target_core); // Set affinity to target core from core 0
  };

  // Register custom thread pool
  spdlog::init_thread_pool(num_items, num_threads, on_thread_start);

  // The create function would automatically use the custom thread pool.
  auto async_file = spdlog::daily_logger_mt<spdlog::async_factory>("async_logger", "logs/");

  async_file.info("Hello World");

}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.