Threads running on different CPU cores in C++ 11

Here is a short program in C++ 11 to see how threads are running on different CPU cores

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>

std::mutex mu;

unsigned long GetCurrentProcessorNumber() {
int CPUInfo[4];
__cpuid(CPUInfo, 1);
return (unsigned)CPUInfo[1] >> 24;
}

void function(int i) {
mu.lock();
std::cout << "Thread Number" << i << " : is Running on CPU " << GetCurrentProcessorNumber() << std::endl;
mu.unlock();
}

int main() {
auto num_threads = 50;
std::vector<std::thread> threads(num_threads);
for (unsigned i = 0; i < num_threads; ++i) {
threads[i] = std::thread(function,i);
}

for (auto& t : threads) {
t.join();
}
system("pause");
return 0;
}



The Output is :


Comments

Popular Posts