Matt Harris
Matt Harris

Reputation: 3544

Using SetThreadAffinityMask() to dynamically choose which threads to run on

I'm writing a benchmarking program and what I want is to run a thread on different cores, one after another. So for example it will run the work on just core 0, then on cores 0,1, then on cores 0,1,2,3 and then on 0,1,2,3,4,5,6,7 (If the machine has 8 cores). I'm confused about the second parameter I need to pass to SetThreadAffinityMask().

I can either pass a decimal number or a hexadecimal it seems. In hex, I can pass:

0x0001 for core 0,
0x0003 for cores 0,1,
0x000F for cores 0,1,2,3

But I am struggling to work out how to create these values dynamically. Essentially for any given number of cores I need to be able to get the hex value to set the affinity to all cores up to that number. Any help with where to start would be great.

Upvotes: 0

Views: 916

Answers (2)

James McNellis
James McNellis

Reputation: 355079

"All of the cores up to (but not including) N" requires the mask value 2N - 1, so:

(static_cast<DWORD_PTR>(1) << N) - 1;

Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129374

The bit values are 1 << core_number. So if you have something like this:

vector<int> cpus_to_use = { 1, 3, 9, 11 }; 

then you can make the affinity mask by:

int mask = 0;
for( i : cpus_to_use) 
    mask |= 1 << i; 

If you just want to set ALL bits, then (1 << num_cores) - 1 will give you num_cores bits set.

Upvotes: 1

Related Questions