参考:https://blog.csdn.net/wuhui_gdnt/article/details/51280906
通过编程设置CPU亲和性
(1) taskset 命令行工具让我们控制整个进程的CPU亲和性;
(2)在Linux上,我们可以使用pthread特定的pthread_setafftinity_np函数。通过设置其亲和性将每个线程固定到单个CPU:
code:
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <queue>
#include <map>
#include <thread>
#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, const char** argv)
{
constexpr unsigned num_threads = 4;
// A mutex ensures orderly access to std::cout from multiplethreads.
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));
while (1)
{
{
// Use a lexical scope and lock_guard to safely lock the mutexonly
// for the duration of std::cout usage.
std::lock_guard<std::mutex> iolock(iomutex);
std::cout<< "Thread #" << i << ":on CPU " <<sched_getcpu() << "\n";
}
// Simulate important work done by the tread by sleeping for abit...
std::this_thread::sleep_for(std::chrono::milliseconds(900));
}});
// Create a cpu_set_t object representing a set of CPUs. Clear itand mark
// only CPU i as set.
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(i,&cpuset);
int rc =pthread_setaffinity_np(threads[i].native_handle(),sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
}
}
for (auto& t : threads) {
t.join();
}
return 0;
}
CmakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
set(version_ 0.4.8)
project(test_demo VERSION ${version_})
set(CMAKE_BUILD_TYPE "Release")
set(CMAKE_CXX_FLAGS "-std=c++14 -pthread")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -Wall -g")
include_directories(
./
)
add_executable(test_demo setThread2Cpu.cpp )
target_link_libraries(test_demo -lpthread)
运行结果:
Thread #0:on CPU 0
Thread #1:on CPU 1
Thread #2:on CPU 2
Thread #3:on CPU 3
Thread #0:on CPU 0
Thread #1:on CPU 1
Thread #3:on CPU 3
Thread #2:on CPU 2
Thread #0:on CPU 0
Thread #1:on CPU 1
Thread #3:on CPU 3
Thread #2:on CPU 2