make two thread in two different core in C++

2019-04-17 06:33发布

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.

2条回答
Animai°情兽
2楼-- · 2019-04-17 06:49

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.

查看更多
淡お忘
3楼-- · 2019-04-17 07:03

For posix, check out pthread_getaffinity_np and pthread_setaffinity_np

查看更多
登录 后发表回答