i have 2 thread t1 , t2 tries print alrenatively through semaphore signaling. each thread prints 10 times, sometime, both gets blocked @ waitforsingleobject , not print anything. doing wrong.can please let me know how solve , rid of 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 thread affinity t1 not done\n")); } while(i!=10) { waitforsingleobject(hthreadsemaphore2,infinite); i++; printf("thread 1 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 thread affinity t1 not done\n")); } while(i!=10) { waitforsingleobject(hthreadsemaphore1,infinite); i++; printf("thread 2 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 need create both semaphores before create (and run) threads. i'm assuming _beginthreadex
starts thread running immediately...
if check return codes semaphore takes , gives, on runs deadlocks, errors returned? i'm thinking threads have started before semaphores created...
Comments
Post a Comment