我有两个线程 T1 和 T2 试图通过信号量信号进行打印。每个线程打印 10 次,但有时,两者都在 WaitforSingleObject 处被阻塞并且不打印任何内容。我做错了什么吗?请让我知道如何解决这个问题并摆脱这个问题。
HANDLE hThreadSemaphore1,hThreadSemaphore2;
void T1(void *param) {
static int i=0;
ReleaseSemaphore(hThreadSemaphore2, 1, NULL);
BOOL success = SetThreadAffinityMask(GetCurrentThread(),1);
_tprintf (_T("SetThreadAffinityMask PAssed: %d\n"), GetLastError());
if(success ==0) {
_tprintf (_T("Setting the Thread Affinity for T1 could not be done\n"));
}
while(i!=10) {
WaitForSingleObject(hThreadSemaphore2,INFINITE);
i++;
printf("Thread 1 is Running %d!\n",i);
ReleaseSemaphore(hThreadSemaphore1, 1, NULL);
}
_endthread();
}
T2:
void T2(void *param) {
static int i=0;
BOOL success = SetThreadAffinityMask(GetCurrentThread(),1);
_tprintf (_T("SetThreadAffinityMask PAssed: %d\n"), GetLastError());
if(success ==0) {
_tprintf (_T("Setting the Thread Affinity for T1 could not be done\n"));
}
while(i!=10) {
WaitForSingleObject(hThreadSemaphore1,INFINITE);
i++;
printf("Thread 2 is Running %d!\n",i);
ReleaseSemaphore(hThreadSemaphore2, 1, NULL);
}
_endthread();
}
主要的
int _tmain(int argc, _TCHAR* argv[]) {
unsigned long val1,val2;
HANDLE handle1,handle2;
handle1 = (HANDLE) _beginthreadex(NULL,0, (unsigned int (__stdcall *)(void *))T1,NULL,0,(unsigned int*)&val1); // create thread
char SemName[80];
sprintf(SemName, "ThreadSem_0x%x",val1);
hThreadSemaphore1 = CreateSemaphore(NULL, 0, 5,(LPCWSTR) SemName);
handle2 = (HANDLE) _beginthreadex(NULL,0, (unsigned int (__stdcall *)(void *))T2,NULL,0,(unsigned int*)&val2); // create thread
sprintf(SemName, "ThreadSem_0x%x",val2);
hThreadSemaphore2 = CreateSemaphore(NULL, 0, 5,(LPCWSTR) SemName);
HANDLE process = GetCurrentProcess();
getch();
return 0;
}