Parameters
hThread
[in] Handle to the thread whose affinity mask is to be set.
This handle must have the THREAD_SET_INFORMATION and THREAD_QUERY_INFORMATION access rights. For more information, see Thread Security and Access Rights.
dwThreadAffinityMask
[in] Affinity mask for the thread.
Windows Me/98/95: This value must be 1.
Return Values
If the function succeeds, the return value is the thread's previous affinity mask.
Windows Me/98/95: The return value is 1. To succeed, hThread must be valid and dwThreadAffinityMask must be 1.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
A thread affinity mask is a bit vector in which each bit represents the processors that a thread is allowed to run on.
A thread affinity mask must be a proper subset of the process affinity mask for the containing process of a thread. A thread is only allowed to run on the processors its process is allowed to run on.
通過(guò)調(diào)用SetThreadAffinityMask,就能為各個(gè)線程設(shè)置親緣性屏蔽:
- DWORD_PTR SetThreadAffinityMask(HANDLE hThread, DWORD_PTR dwThreadAffinityMask);
該函數(shù)中的h T h r e a d參數(shù)用于指明要限制哪個(gè)線程, dwThreadAffinityMask用于指明該線程能夠在哪個(gè)CPU上運(yùn)行。dwThreadAffinityMask必須是進(jìn)程的親緣性屏蔽的相應(yīng)子集。返回值是線程的前一個(gè)親緣性屏蔽。
因此,若要將3個(gè)線程限制到CPU1、2和3上去運(yùn)行,可以這樣操作:
-
-
- SetThreadAffinityMask(hThread0, 0x00000001);
-
-
-
- SetThreadAffinityMask(hThread1, 0x00000002);
-
- SetThreadAffinityMask(hThread2, 0x00000003);
-
- SetThreadAffinityMask(hThread3, 0x00000004);
本文來(lái)自CSDN博客,轉(zhuǎn)載請(qǐng)標(biāo)明出處:http://blog.csdn.net/W511522329/archive/2010/03/06/5352597.aspx
- #include "stdafx.h"
- #include <windows.h>
- #include <string>
- #include <iostream>
- void running(int seconds) {
- Sleep(seconds*1000);
- std::cout<<"sleep for "<<seconds<<"(s)"<<std::endl;
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- SetThreadAffinityMask(GetCurrentThread(), 1);
- LARGE_INTEGER start, end;
- LARGE_INTEGER freq;
-
- QueryPerformanceFrequency(&freq);
- QueryPerformanceCounter(&start);
-
-
- std::cout<<"start.QuadPart = "<<start.QuadPart<<std::endl;
- running(10);
- QueryPerformanceCounter(&end);
- std::cout<<"end.QuadPart = "<<end.QuadPart<<std::endl;
-
- std::cout<<"consume value = end.QuadPart - start.QuadPart = "<<(end.QuadPart - start.QuadPart)<<std::endl;
- std::cout<<"(consume value/(double)freq.QuadPart) Time consumed = "<<(end.QuadPart - start.QuadPart)/(double)freq.QuadPart<<"(s)"<<std::endl;
- return 0;
- }
start.QuadPart = 49102789906513
sleep for10(s)
end.QuadPart = 49127801303663
consume value = end.QuadPart - start.QuadPart = 25011397150
(consume value/(double)freq.QuadPart) Time consumed = 10.0046(s)