将线程绑定在指定的CPU上运行

将线程绑定在指定的CPU上运行

void main()
{
    
    
	int cpu_num = sysconf(_SC_NPROCESSORS_CONF);
	pthread_t tid;
	cpu_set_t mask;
	cpu_set_t get;

	CPU_ZERO(&mask);
	CPU_ZERO(&get);
	// 绑定在第三个cpu核心上
	CPU_SET(3, &mask);
	pthread_create(&tid, NULL, f_thread, (void *)argv);
	// 线程绑定指定cpu
	pthread_setaffinity_np(tid, sizeof(cpu_set_t), &mask);
	// 获取线程在哪个cpu
	pthread_getaffinity_np(tid, sizeof(get), &get)
	// 判断在哪个cpu
	for (j = 0; j < cpu_num; j++) {
    
    
		if (CPU_ISSET(j, &get)) {
    
    
			printf("thread %d is running in processor %d\n", (int)(tid[i]), j);
			break;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/G_Super_Mouse/article/details/109790098
今日推荐