File: thr_daemon_exit_libc.c

package info (click to toggle)
valgrind 1%3A3.24.0-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 176,332 kB
  • sloc: ansic: 795,029; exp: 26,134; xml: 23,472; asm: 14,393; cpp: 9,397; makefile: 7,464; sh: 6,122; perl: 5,446; python: 1,498; javascript: 981; awk: 166; csh: 1
file content (72 lines) | stat: -rw-r--r-- 1,983 bytes parent folder | download | duplicates (7)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* Creates several daemon threads and non-daemon threads.
   Tests that the process can exit even if the daemon threads are still running,
   as per thr_create(3C). */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <thread.h>
#include <unistd.h>

#define DAEMON_THREADS 5
#define NON_DAEMON_THREADS 6
#define SLEEP_100_MS usleep(100 * 1000)

static pthread_barrier_t barrier;

void *daemon_thread_func(void *arg) {
   size_t index = (size_t) arg;
   printf("DAEMON thread #%zu running\n", index); fflush(stdout);
   pthread_barrier_wait(&barrier);

   /* Give the non-daemon threads enough time to exit. */
   sleep(10);
   printf("DAEMON thread #%zu still running?!\n", index); fflush(stdout);
   return NULL;
}

void *normal_thread_func(void *arg) {
   size_t index = (size_t) arg;
   printf("non-daemon thread #%zu running\n", index); fflush(stdout);
   pthread_barrier_wait(&barrier);

   sleep(2);
   return NULL;
}

int main(void) {
   size_t i;
   int ret = pthread_barrier_init(&barrier, NULL,
                                  DAEMON_THREADS + NON_DAEMON_THREADS + 1);
   if (ret != 0) {
      fprintf(stderr, "pthread_barrier_init failed: %s\n", strerror(ret));
      return 1;
   }

   for (i = 0; i < DAEMON_THREADS; i++) {
      ret = thr_create(NULL, 0, daemon_thread_func, (void *) i,
                       THR_DAEMON, NULL);
      if (ret != 0) {
         fprintf(stderr, "thr_create failed: %s\n", strerror(ret));
         return 1;
      }
      SLEEP_100_MS;
   }

   for (i = 0; i < NON_DAEMON_THREADS; i++) {
      ret = thr_create(NULL, 0, normal_thread_func, (void *) i, 0, NULL);
      if (ret != 0) {
         fprintf(stderr, "thr_create failed: %s\n", strerror(ret));
         return 1;
      }
      SLEEP_100_MS;
   }

   pthread_barrier_wait(&barrier);

   printf("MAIN thread exiting\n");
   /* Exit only the main thread, not whole process.
      That is, do not exit(0) or return(0). */
   thr_exit(NULL);
}