How do I pin threads and set affinities (platform-specific)?

Learn how to pin threads and set CPU affinities in C++ for optimal performance on different platforms such as Windows and Linux. This guide provides code snippets and detailed explanations to help you efficiently manage thread assignments to specific CPU cores.
C++, Threads, CPU Affinity, Windows, Linux, Performance Optimization
// Example for setting thread affinity in Windows #include #include DWORD WINAPI ThreadFunction(LPVOID lpParam) { // Thread code here return 0; } int main() { HANDLE thread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, NULL); // Set thread affinity to CPU 0 DWORD_PTR processAffinityMask = 1; SetThreadAffinityMask(thread, processAffinityMask); WaitForSingleObject(thread, INFINITE); CloseHandle(thread); return 0; } // Example for setting thread affinity in Linux #include #include #include void* ThreadFunction(void* arg) { // Thread code here return nullptr; } int main() { pthread_t thread; pthread_create(&thread, NULL, ThreadFunction, NULL); // Set thread affinity to CPU 0 cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(0, &cpuset); pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); pthread_join(thread, NULL); return 0; }

C++ Threads CPU Affinity Windows Linux Performance Optimization