有时5次,2-3次,Threads在waitforsingleobject中出现死锁

时间:2013-05-05 23:18:05

标签: deadlock semaphore waitforsingleobject

我有两个线程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;
}

1 个答案:

答案 0 :(得分:1)

我认为您需要在创建(并运行)线程之前创建两个信号量。我假设_beginthreadex立即启动线程运行...

如果检查信号量中的返回码,则在遇到死锁的运行中,是否会返回错误?我认为线程可以在创建所有信号量之前启动......