Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

https://blog.csdn.net/zfjBIT/article/details/105846212

c++11的std::thread可以通过native_handle()来获取底层的pthread_t,然后照样使用pthread_t的函数pthread_setaffinity_np来绑核

#include <iostream>
#include <vector>
#include <thread>
#include <pthread.h>
#include <mutex>

int main(int argc, const char **argv)
{
    constexpr unsigned num_threads = 4;
    std::mutex iomutex;
    std::vector<std::thread> threads(num_threads);
    for (unsigned i = 0; i < num_threads; ++i)
    {
        threads[i] = std::thread([&iomutex, i]
                                 {std::this_thread::sleep_for(std::chrono::milliseconds(20));
        // endless loop
          while (1)
          {
              {
                    std::lock_guard<std::mutex> iolock(iomutex);
                    std::cout<< "Thread #" << i << ":on CPU " <<sched_getcpu() << "\n";
              }
            // Simulate work
            std::this_thread::sleep_for(std::chrono::milliseconds(900));
            } });

        // 这里
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);                                                                       // clean cpuset
        CPU_SET(i, &cpuset);                                                                     // only contain cpu i
        int rc = pthread_setaffinity_np(threads[i].native_handle(), sizeof(cpu_set_t), &cpuset); // bind threads[i] to cpu i

        if (rc != 0)
        {
            std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
        }
    }

    for (auto &t : threads)
        t.join();

    return 0;
}
cmake_minimum_required(VERSION 3.0.0)
 
project(bind_cpu_test)
 
set(CMAKE_CXX_FLAGS "-std=c++11")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -Wall -g")
 
add_executable(main main.cpp )
target_link_libraries(main pthread)  # 注意这里链接pthread库

评论