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 <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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JoannaJuanCV

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值