make two thread in two different core in C++

2019-04-17 07:07发布

问题:

I read some articles about this problem. The case seems not easy. I want to create two different thread in two core. the articles that I read were too complicated. I even couldn't create a simple thread based on those articles. at the other hand I need to understand how many cores a computer have to make available as a choice for using both core or just create threads on one core. I want to do them on windows. Any help would highly welcome

P.S: I am not that pro on C++. So please if it is possible guide me with easier ways.

回答1:

Though it's generally a lousy idea (the thread scheduler usually does a better job on its own), the basic idea would be:

HANDLE thread_a = CreateThread(/* ... */);
HANDLE thread_b = CreateThread(/* ... */);

SetThreadAffinityMask(thread_a, 1 << 0);
SetThreadAffinityMask(thread_b, 1 << 1);

Note that the 1<<0 and 1<<1 could just as easily be written as 1 and 2 respectively -- I was just trying to make explicit the fact that each bit position represents a processor.



回答2:

For posix, check out pthread_getaffinity_np and pthread_setaffinity_np