1/* Unit test for drd that triggers a race on the use of a POSIX condition
2   variable. By Bart Van Assche.
3*/
4
5#include <assert.h>
6#include <stdio.h>      // printf()
7#include <pthread.h>
8#include <unistd.h>    // usleep()
9
10
11// Local functions declarations.
12
13static void* thread_func(void* thread_arg);
14
15
16// Local variables.
17
18static pthread_mutex_t s_mutex;
19static pthread_cond_t  s_cond;
20static int             s_use_mutex = 0;
21
22
23// Function definitions.
24
25int main(int argc, char** argv)
26{
27  int optchar;
28  pthread_t threadid;
29
30  while ((optchar = getopt(argc, argv, "m")) != EOF)
31  {
32    switch (optchar)
33    {
34    case 'm':
35      s_use_mutex = 1;
36      break;
37    default:
38      assert(0);
39    }
40  }
41
42  pthread_cond_init(&s_cond, 0);
43  pthread_mutex_init(&s_mutex, 0);
44  pthread_mutex_lock(&s_mutex);
45
46  pthread_create(&threadid, 0, thread_func, 0);
47
48  pthread_cond_wait(&s_cond, &s_mutex);
49  pthread_mutex_unlock(&s_mutex);
50
51  pthread_join(threadid, 0);
52
53  pthread_mutex_destroy(&s_mutex);
54  pthread_cond_destroy(&s_cond);
55
56  return 0;
57}
58
59static void* thread_func(void* thread_arg)
60{
61  // Wait until the main thread has entered pthread_cond_wait().
62  pthread_mutex_lock(&s_mutex);
63  pthread_mutex_unlock(&s_mutex);
64
65  // Signal the condition variable.
66  if (s_use_mutex) pthread_mutex_lock(&s_mutex);
67  pthread_cond_signal(&s_cond);
68  if (s_use_mutex) pthread_mutex_unlock(&s_mutex);
69
70  return 0;
71}
72