File: testpthread.cc

package info (click to toggle)
apt-cacher-ng 2-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,032 kB
  • ctags: 1,705
  • sloc: cpp: 16,869; sh: 536; ansic: 404; perl: 377; makefile: 124
file content (39 lines) | stat: -rw-r--r-- 950 bytes parent folder | download | duplicates (14)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <pthread.h>
#include <errno.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;

void* stop_it(void *)
{
   pthread_mutex_lock(&mx);
   pthread_cond_broadcast(&cond);
   pthread_mutex_unlock(&mx);
   return NULL;
}

int main(void)
{
   // no problem with small type
   const struct timespec timeout = {9223372036854775807L, 12345};
   if(sizeof(timeout.tv_sec) < 8)
      return 0;
   for(int i=0;i<30;++i)
   {
      pthread_mutex_lock(&mx);
      pthread_t thr;
      if(pthread_create(&thr,0,stop_it,0))
         return -1;
      switch(pthread_cond_timedwait(&cond, &mx, &timeout))
      {
         case EINTR:
            continue; // loaded system, or killed by user?
         case 0:
            return 0; // correctly awaken = good
         default:
            return 1; // buggy implementation
      }
      pthread_mutex_unlock(&mx);
      pthread_join(thr, 0);
   }
   return -2;
}