There are two CPU in my computer, named CPU0 and CPU1.
First,I created 12 thread,and I want this program's every thread to run at CPU0, but after I used the fuction
setthreadaffinitymask
, it does not work. Is there anything wrong with the program?
#include <windows.h>
#include <stdio.h>
#define MAX_SEM_COUNT 10
#define THREADCOUNT 12
HANDLE ghSemaphore;
DWORD WINAPI ThreadProc( LPVOID );
void main()
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
ghSemaphore = CreateSemaphore(
NULL, MAX_SEM_COUNT, MAX_SEM_COUNT, NULL); if (ghSemaphore == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
return;
}
for( i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL, 0, (LPTHREAD_START_ROUTINE) ThreadProc,
NULL, CREATE_SUSPENDED, &ThreadID);
if( aThread[i] == NULL )
{
printf("CreateThread error: %d\n", GetLastError());
return;
}
SetThreadAffinityMask(aThread[i],0x00000001);
ResumeThread(aThread[i]);
}
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghSemaphore);
system("pause");
}
DWORD WINAPI ThreadProc( LPVOID lpParam )
{
DWORD dwWaitResult;
BOOL bContinue=TRUE;
while(bContinue)
{
dwWaitResult = WaitForSingleObject(
ghSemaphore, 0L);
switch (dwWaitResult)
{
case WAIT_OBJECT_0:
printf("Thread %d: wait succeeded\n", GetCurrentThreadId());
bContinue=FALSE;
Sleep(5);
if (!ReleaseSemaphore(
ghSemaphore, 1, NULL) ) {
printf("ReleaseSemaphore error: %d\n", GetLastError());
}
break;
case WAIT_TIMEOUT:
printf("Thread %d: wait timed out\n", GetCurrentThreadId());
break;
}
}
return TRUE;
}