xref: /reactos/modules/rostests/tests/mutex/mutex.c (revision 845faec4)
1 #include <windows.h>
2 #include <string.h>
3 #include <stdio.h>
4 
5 
6 HANDLE OutputHandle;
7 HANDLE InputHandle;
8 
9 HANDLE hThread[2];
10 DWORD dwCounter = 0;
11 HANDLE hMutex;
12 
13 
14 void dprintf(char* fmt, ...)
15 {
16    va_list args;
17    char buffer[255];
18 
19    va_start(args,fmt);
20    vsprintf(buffer,fmt,args);
21    WriteConsoleA(OutputHandle, buffer, strlen(buffer), NULL, NULL);
22    va_end(args);
23 }
24 
25 
26 DWORD WINAPI thread1(LPVOID crap)
27 {
28   DWORD dwError = 0;
29   DWORD i;
30 
31   dprintf("Thread 1 running!\n");
32 
33   for (i = 0; i < 10; i++)
34     {
35       dwError = WaitForSingleObject(hMutex, INFINITE);
36       if (dwError == WAIT_FAILED)
37 	{
38 	  dprintf("Thread2: WaitForSingleObject failed!\n");
39 	  return 1;
40 	}
41       else if (dwError == WAIT_ABANDONED_0)
42 	{
43 	  dprintf("Thread2: WaitForSingleObject returned WAIT_ABANDONED_0\n");
44 	}
45 
46       dprintf("Thread1: dwCounter : %lu -->", dwCounter);
47       dwCounter++;
48       dprintf(" %lu\n", dwCounter);
49       ReleaseMutex(hMutex);
50     }
51 
52   dprintf("Thread 1 done!\n");
53 
54   return 1;
55 }
56 
57 DWORD WINAPI thread2(LPVOID crap)
58 {
59   DWORD dwError = 0;
60   DWORD i;
61   dprintf("Thread 2 running!\n");
62 
63   for (i = 0; i < 10; i++)
64     {
65       dwError = WaitForSingleObject(hMutex, INFINITE);
66       if (dwError == WAIT_FAILED)
67 	{
68 	  dprintf("Thread2: WaitForSingleObject failed!\n");
69 	  return 1;
70 	}
71       else if (dwError == WAIT_ABANDONED_0)
72 	{
73 	  dprintf("Thread2: WaitForSingleObject returned WAIT_ABANDONED_0\n");
74 	}
75 
76       dprintf("Thread2: dwCounter : %lu -->", dwCounter);
77       dwCounter++;
78       dprintf(" %lu\n", dwCounter);
79       ReleaseMutex(hMutex);
80     }
81 
82   dprintf("Thread 2 done!\n");
83 
84   return 1;
85 }
86 
87 
88 int main(int argc, char* argv[])
89 {
90   DWORD dwError;
91   DWORD id1,id2;
92 
93   AllocConsole();
94   InputHandle = GetStdHandle(STD_INPUT_HANDLE);
95   OutputHandle =  GetStdHandle(STD_OUTPUT_HANDLE);
96 
97   dprintf("Calling CreateMutex()\n");
98   hMutex = CreateMutexW(NULL, FALSE, L"TestMutex");
99   if (hMutex == INVALID_HANDLE_VALUE)
100     {
101       dprintf("CreateMutex() failed! Error: %lu\n", GetLastError());
102       return 0;
103     }
104   dprintf("CreateMutex() succeeded!\n");
105 
106   hThread[0] = CreateThread(0, 0, thread1, 0, 0, &id1);
107   hThread[1] = CreateThread(0, 0, thread2, 0, 0, &id2);
108 
109   dprintf("Calling WaitForMultipleObject()\n");
110   dwError = WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
111   dprintf("WaitForMultipleObject() Error: %lu\n", dwError);
112 
113   CloseHandle(hThread[0]);
114   CloseHandle(hThread[1]);
115 
116   CloseHandle(hMutex);
117 
118   dprintf("Main thread done!\n");
119 
120   return 0;
121 }
122