FreeRDP
TestSynchThread.c
1 
2 #include <winpr/crt.h>
3 #include <winpr/synch.h>
4 #include <winpr/thread.h>
5 
6 static DWORD WINAPI test_thread(LPVOID arg)
7 {
8  WINPR_UNUSED(arg);
9  Sleep(100);
10  ExitThread(0);
11  return 0;
12 }
13 
14 int TestSynchThread(int argc, char* argv[])
15 {
16  DWORD rc = 0;
17  HANDLE thread = NULL;
18 
19  WINPR_UNUSED(argc);
20  WINPR_UNUSED(argv);
21 
22  thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL);
23 
24  if (!thread)
25  {
26  printf("CreateThread failure\n");
27  return -1;
28  }
29 
30  /* TryJoin should now fail. */
31  rc = WaitForSingleObject(thread, 0);
32 
33  if (WAIT_TIMEOUT != rc)
34  {
35  printf("Timed WaitForSingleObject on running thread failed with %" PRIu32 "\n", rc);
36  return -3;
37  }
38 
39  /* Join the thread */
40  rc = WaitForSingleObject(thread, INFINITE);
41 
42  if (WAIT_OBJECT_0 != rc)
43  {
44  printf("WaitForSingleObject on thread failed with %" PRIu32 "\n", rc);
45  return -2;
46  }
47 
48  /* TimedJoin should now succeed. */
49  rc = WaitForSingleObject(thread, 0);
50 
51  if (WAIT_OBJECT_0 != rc)
52  {
53  printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc);
54  return -5;
55  }
56 
57  /* check that WaitForSingleObject works multiple times on a terminated thread */
58  for (int i = 0; i < 4; i++)
59  {
60  rc = WaitForSingleObject(thread, 0);
61  if (WAIT_OBJECT_0 != rc)
62  {
63  printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc);
64  return -6;
65  }
66  }
67 
68  if (!CloseHandle(thread))
69  {
70  printf("CloseHandle failed!");
71  return -1;
72  }
73 
74  thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL);
75 
76  if (!thread)
77  {
78  printf("CreateThread failure\n");
79  return -1;
80  }
81 
82  /* TryJoin should now fail. */
83  rc = WaitForSingleObject(thread, 10);
84 
85  if (WAIT_TIMEOUT != rc)
86  {
87  printf("Timed WaitForSingleObject on running thread failed with %" PRIu32 "\n", rc);
88  return -3;
89  }
90 
91  /* Join the thread */
92  rc = WaitForSingleObject(thread, INFINITE);
93 
94  if (WAIT_OBJECT_0 != rc)
95  {
96  printf("WaitForSingleObject on thread failed with %" PRIu32 "\n", rc);
97  return -2;
98  }
99 
100  /* TimedJoin should now succeed. */
101  rc = WaitForSingleObject(thread, 0);
102 
103  if (WAIT_OBJECT_0 != rc)
104  {
105  printf("Timed WaitForSingleObject on dead thread failed with %" PRIu32 "\n", rc);
106  return -5;
107  }
108 
109  if (!CloseHandle(thread))
110  {
111  printf("CloseHandle failed!");
112  return -1;
113  }
114 
115  /* Thread detach test */
116  thread = CreateThread(NULL, 0, test_thread, NULL, 0, NULL);
117 
118  if (!thread)
119  {
120  printf("CreateThread failure\n");
121  return -1;
122  }
123 
124  if (!CloseHandle(thread))
125  {
126  printf("CloseHandle failed!");
127  return -1;
128  }
129 
130  return 0;
131 }