c++11 thread 线程绑定CPU方法

参考:https://blog.csdn.net/wuhui_gdnt/article/details/51280906

通过编程设置CPU亲和性

(1) taskset 命令行工具让我们控制整个进程的CPU亲和性;

(2)在Linux上,我们可以使用pthread特定的pthread_setafftinity_np函数。通过设置其亲和性将每个线程固定到单个CPU:

code:

#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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::vectorthreads(num_threads);

  for (unsigned i = 0; i  iolock(iomutex);

                    std::cout<< "Thread #" << i << ":on CPU " <

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

 

你可能感兴趣的:(C/C++编程)