您绝对可以通过在程序中编写例程来做到这一点。
但是你不应该尝试这样做,因为操作系统是管理这些东西的最佳选择。我的意思是用户模式程序不应该尝试这样做。
但是,有时,可以(对于真正的高级用户)实现负载平衡,甚至找出真正的多线程多核问题(数据竞争/缓存一致性......),因为不同的线程将真正在不同的处理器上执行.
话虽如此,如果您仍然想实现我们可以通过以下方式实现。我为您提供了(Windows 操作系统)的伪代码,但它们也可以在 Linux 上轻松完成。
#define MAX_CORE 256
processor_mask[MAX_CORE] = {0};
core_number = 0;
Call GetLogicalProcessorInformation();
// From Here we calculate the core_number and also we populate the process_mask[] array
// which would be used later on to set to run different threads on different CORES.
for(j = 0; j < THREAD_POOL_SIZE; j++)
Call SetThreadAffinityMask(hThread[j],processor_mask[j]);
//hThread is the array of handles of thread.
//Now if your number of threads are higher than the actual number of cores,
// you can use reset the counters(j) once you reach to the "core_number".
调用上述例程后,线程将始终以下列方式执行:
Thread1-> Core1
Thread2-> Core2
Thread3-> Core3
Thread4-> Core4
Thread5-> Core5
Thread6-> Core6
Thread7-> Core7
Thread8-> Core8
Thread9-> Core1
Thread10-> Core2
...............
有关更多信息,请参阅手册/MSDN 以了解有关这些概念的更多信息。