c++线程绑定cpu核心,简单记录

绑定,在线程函数内使用

	cpu_set_t mask;
	CPU_ZERO(&mask);

	CPU_SET(6, &mask); //6指核心编号
	pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);

查询线程绑定,在线程函数内使用

		cpu_set_t get;
		CPU_ZERO(&get);
		if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0)
		{
			fprintf(stderr, "get thread affinity failed\n");
		}
		for (int i = 0; i < 20; i++)
			if (CPU_ISSET(i, &get))
			{
				printf("thread %ld is running in processor %d\n", pthread_self(), i);
			}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Windows下,可以使用`SetThreadAffinityMask`函数将线到指CPU核心上。以下是一个示例代码,演示了如何使用C++11标准将线到指CPU核心上: ```cpp #include <iostream> #include <thread> #include <Windows.h> void bindThreadToCore(std::thread& thread, int core) { // 获取线程的原生句柄 HANDLE nativeThread = thread.native_handle(); // 将线到指CPU核心 DWORD_PTR affinityMask = (DWORD_PTR)1 << core; DWORD_PTR previousMask = SetThreadAffinityMask(nativeThread, affinityMask); // 检查是否成功 if (previousMask == 0) { std::cerr << "Failed to bind thread to CPU core " << core << std::endl; } else { std::cout << "Thread bound to CPU core " << core << std::endl; } } void myFunction() { // 在这里执行需要在特CPU核心上的操作 } int main() { int core = 0; // 要CPU核心号 std::thread threadObj(myFunction); bindThreadToCore(threadObj, core); // 等待线程完成 threadObj.join(); return 0; } ``` 在这个示例代码中,我们首先义了一个名为`bindThreadToCore`的函数,它接受一个`std::thread`对象和一个CPU核心号作为参数。在`bindThreadToCore`函数中,我们首先使用`std::thread::native_handle()`函数获取线程的原生句柄。然后,我们使用`SetThreadAffinityMask`函数将线到指CPU核心上。 在`main`函数中,我们创建了一个名为`threadObj`的`std::thread`对象,并调用`bindThreadToCore`函数将该线程对象到指CPU核心上。然后,我们等待线程完成,最后输出CPU核心号。 需要注意的是,该方法是Windows特的,并且依赖于Windows API函数`SetThreadAffinityMask`。请确保在Windows环境下编译和运行该代码。 希望这可以帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

初级蜗牛

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

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

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

打赏作者

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

抵扣说明:

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

余额充值