1 /* fivemutex.c: hungry philosophers problem
3 * (c) Copyright D.W.Howells 2000.
10 #define ERR(X,Y) do { if (X) { perror(""Y""); return 1; } } while(0)
15 const char *names[] = {
16 "five/1", "five/2", "five/3", "five/4", "five/5"
19 DWORD WINAPI child(LPVOID tparam)
21 HANDLE left, right, first, second;
22 const char *lname, *rname;
23 int pid = (int) tparam;
27 rname = names[(pid+1)%5];
30 left = CreateMutex(NULL,0,lname); ERR(!left,"create left");
31 right = CreateMutex(NULL,0,rname); ERR(!left,"create right");
33 printf("[%d] left: %p [%s]\n",pid,left,lname);
34 printf("[%d] right: %p [%s]\n",pid,right,rname);
36 /* pick the forks up in numerical order, else risk starvation */
37 if (pid%5 < (pid+1)%5) {
47 /* grab the left mutex */
48 wt = WaitForMultipleObjects(1,&first,0,INFINITE);
49 if (wt!=WAIT_OBJECT_0)
52 /* grab the right mutex */
53 wt = WaitForMultipleObjects(1,&second,0,INFINITE);
54 if (wt!=WAIT_OBJECT_0)
60 /* pass the mutexes */
61 ERR(!ReleaseMutex(left),"release left");
62 ERR(!ReleaseMutex(right),"release right");
68 printf("[%d] obtained mutex __1__\n",pid);
70 case WAIT_ABANDONED_0:
71 case WAIT_ABANDONED_0+1:
72 printf("[%d] abandoned wait\n",pid);
75 printf("[%d] wait timed out\n",pid);
78 ERR(1,"WaitForMultipleObjects");
84 /* close the handles */
85 ERR(!CloseHandle(left),"close left");
86 ERR(!CloseHandle(right),"close right");
98 for (loop=0; loop<5; loop++) {
100 hThread[loop] = CreateThread(NULL, /* thread attributes */
102 child, /* start address */
103 (void*)loop, /* parameter */
104 0, /* creation flags */
109 ERR(1,"CreateThread");
113 WaitForMultipleObjects(5,hThread,0,RUNLENGTH*1000);
115 for (loop=0; loop<5; loop++)
116 TerminateThread(hThread[loop],0);
118 for (loop=0; loop<5; loop++)
119 printf("[%d] ate %d times (%d times per second)\n",
120 loop,count[loop],count[loop]/RUNLENGTH