我有两个线程T1和T2,它们试图通过信号量信号自动打印。每个线程打印10次,但有时,两个线程都会在WaitforSingleObject处被阻塞,并且不打印任何内容。我做了什么事了吗? wrong.Can,请让我知道如何解决这个问题。
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();
}Main
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;
}发布于 2013-05-06 07:59:37
我认为在创建(和运行)线程之前,您需要创建这两个信号量。我假设_beginthreadex会立即启动线程运行...
如果你检查信号量接受和给予的返回代码,在死锁的运行中,你会得到一个返回的错误吗?我认为线程可能在创建所有信号量之前就已经开始了……
https://stackoverflow.com/questions/16390129
复制相似问题