VMM: Make new virtio implementation work with new vmm 2LS
[akaros.git] / tests / pthread_cleanup_test.c
1 #include <pthread.h>
2 #include <sys/types.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <errno.h>
7
8 #define handle_error_en(en, msg) \
9                   do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
10
11 static volatile int done = 0;
12 static volatile int cleanup_pop_arg = 0;
13 static volatile int cnt = 0;
14
15 static void
16 cleanup_handler(void *arg)
17 {
18         printf("Running Cleanup Handler\n");
19 }
20
21 static void *
22 thread_start(void *arg)
23 {
24         time_t start, curr;
25         printf("Pushing Cleanup Handler\n");
26         pthread_cleanup_push(cleanup_handler, NULL);
27         while (!done)
28                 cnt++;
29         printf("Popping Cleanup Handler: %d\n", cleanup_pop_arg);
30         pthread_cleanup_pop(cleanup_pop_arg);
31         return NULL;
32 }
33
34 int
35 main(int argc, char *argv[])
36 {
37         pthread_t thr;
38         int s;
39         void *res;
40
41         if (argc == 2) {
42                 cleanup_pop_arg = atoi(argv[1]);
43         } else {
44                 printf("You must supply either 0 or 1 as an argument to "
45                        "run the pop handler or not.\n");
46                 exit(EXIT_FAILURE);
47         }
48
49         /* Start a new thread. */
50         s = pthread_create(&thr, NULL, thread_start, NULL);
51         if (s != 0)
52                 handle_error_en(s, "pthread_create");
53
54         /* Allow new thread to run a while, then signal done. */
55         uthread_sleep(2);
56         done = 1;
57
58         s = pthread_join(thr, &res);
59         if (s != 0)
60                 handle_error_en(s, "pthread_join");
61
62         printf("Thread terminated normally; cnt = %d\n", cnt);
63         exit(EXIT_SUCCESS);
64 }