• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "test.h"
2 #include <sys/timeb.h>
3 
4 typedef struct cvthing_t_ cvthing_t;
5 
6 struct cvthing_t_ {
7   pthread_cond_t notbusy;
8   pthread_mutex_t lock;
9   int shared;
10 };
11 
12 static cvthing_t cvthing = {
13   PTHREAD_COND_INITIALIZER,
14   PTHREAD_MUTEX_INITIALIZER,
15   0
16 };
17 
18 enum {
19   NUMTHREADS = 2
20 };
21 
22 void *
mythread(void * arg)23 mythread(void * arg)
24 {
25   assert(pthread_mutex_lock(&cvthing.lock) == 0);
26   cvthing.shared++;
27   assert(pthread_mutex_unlock(&cvthing.lock) == 0);
28 
29   assert(pthread_cond_signal(&cvthing.notbusy) == 0);
30 
31   return (void *) 0;
32 }
33 
34 int
main()35 main()
36 {
37   pthread_t t[NUMTHREADS];
38   struct timespec abstime = { 0, 0 };
39   struct _timeb currSysTime;
40   const DWORD NANOSEC_PER_MILLISEC = 1000000;
41 
42   cvthing.shared = 0;
43 
44   assert((t[0] = pthread_self()) != 0);
45   assert(pthread_gethandle (t[0]) != NULL);
46 
47   assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER);
48 
49   assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER);
50 
51   assert(pthread_mutex_lock(&cvthing.lock) == 0);
52 
53   assert(cvthing.lock != PTHREAD_MUTEX_INITIALIZER);
54 
55   /* get current system time */
56   _ftime(&currSysTime);
57 
58   abstime.tv_sec = currSysTime.time;
59   abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm;
60 
61   abstime.tv_sec += 5;
62 
63   assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == ETIMEDOUT);
64 
65   assert(cvthing.notbusy != PTHREAD_COND_INITIALIZER);
66 
67   assert(pthread_create(&t[1], NULL, mythread, (void *) 1) == 0);
68 
69   _ftime(&currSysTime);
70 
71   abstime.tv_sec = currSysTime.time;
72   abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm;
73 
74   abstime.tv_sec += 5;
75 
76   while (! (cvthing.shared > 0))
77     assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0);
78 
79   assert(cvthing.shared > 0);
80 
81   assert(pthread_mutex_unlock(&cvthing.lock) == 0);
82 
83   assert(pthread_join(t[1], NULL) == 0);
84 
85   assert(pthread_mutex_destroy(&cvthing.lock) == 0);
86 
87   assert(cvthing.lock == NULL);
88 
89   assert(pthread_cond_destroy(&cvthing.notbusy) == 0);
90 
91   assert(cvthing.notbusy == NULL);
92 
93   return 0;
94 }
95