Вопрос

I have two thread T1 and T2 which tries to print alrenatively through semaphore signaling. Each thread prints 10 times, but sometime, both gets blocked at WaitforSingleObject and does not print anything. Am i doing something wrong.Can you please let me know how to solve this and get rid of this problem.

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;
}
Это было полезно?

Решение

I think you need to create both semaphores before you create (and run) your threads. I'm assuming _beginthreadex starts thread running immediately...

If you check the return codes from the semaphore takes and gives, on the runs where it deadlocks, do you get an errors returned? I'm thinking that threads could have started before all semaphores are created...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top