0

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

1 回答 1

1

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

如果您检查信号量获取和给出的返回代码,在它死锁的运行中,您是否会返回错误?我认为线程可能在创建所有信号量之前就已经开始了......

于 2013-05-05T23:59:37.113 回答