cons: disable dangerous conswrites()
[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 cleanup_handler(void *arg)
16 {
17         printf("Running Cleanup Handler\n");
18 }
19
20 static void *thread_start(void *arg)
21 {
22         time_t start, curr;
23
24         printf("Pushing Cleanup Handler\n");
25         pthread_cleanup_push(cleanup_handler, NULL);
26         while (!done)
27                 cnt++;
28         printf("Popping Cleanup Handler: %d\n", cleanup_pop_arg);
29         pthread_cleanup_pop(cleanup_pop_arg);
30         return NULL;
31 }
32
33 int main(int argc, char *argv[])
34 {
35         pthread_t thr;
36         int s;
37         void *res;
38
39         if (argc == 2) {
40                 cleanup_pop_arg = atoi(argv[1]);
41         } else {
42                 printf("You must supply either 0 or 1 as an argument to "
43                        "run the pop handler or not.\n");
44                 exit(EXIT_FAILURE);
45         }
46
47         /* Start a new thread. */
48         s = pthread_create(&thr, NULL, thread_start, NULL);
49         if (s != 0)
50                 handle_error_en(s, "pthread_create");
51
52         /* Allow new thread to run a while, then signal done. */
53         uthread_sleep(2);
54         done = 1;
55
56         s = pthread_join(thr, &res);
57         if (s != 0)
58                 handle_error_en(s, "pthread_join");
59
60         printf("Thread terminated normally; cnt = %d\n", cnt);
61         exit(EXIT_SUCCESS);
62 }