6dc52fac71d43ca38fa1a344657b29f2d86a0bc0
[akaros.git] / tests / pthread_test.c
1 #include <rstdio.h>
2 #include <pthread.h>
3
4 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
5 #define printf_safe(...) \
6         pthread_mutex_lock(&lock); \
7         printf(__VA_ARGS__); \
8         pthread_mutex_unlock(&lock);
9
10 pthread_t t1;
11 pthread_t t2;
12 pthread_t t3;
13
14 pthread_t my_threads[10];
15 void *my_retvals[10];
16
17 __thread int my_id;
18 void *thread(void* arg)
19 {       
20         for (int i = 0; i < 10; i++) {
21                 printf_safe("[A] pthread %d on vcore %d\n", pthread_self()->id, vcore_id());
22                 pthread_yield();
23                 printf_safe("[A] pthread %d returned from yield on vcore %d\n",
24                             pthread_self()->id, vcore_id());
25         }
26         return (void*)(pthread_self()->id);
27 }
28
29 int main(int argc, char** argv) 
30 {
31         void *retval1 = 0;
32         void *retval2 = 0;
33
34         printf_safe("[A] About to create thread 1\n");
35         pthread_create(&t1, NULL, &thread, NULL);
36         printf_safe("[A] About to create thread 2\n");
37         pthread_create(&t2, NULL, &thread, NULL);
38         printf_safe("About to create thread 3\n");
39         pthread_create(&t3, NULL, &thread, NULL);
40         while(1);
41
42         while (1) {
43                 for (int i = 1; i < 10; i++) {
44                         printf_safe("[A] About to create thread %d\n", i);
45                         pthread_create(&my_threads[i], NULL, &thread, NULL);
46                 }
47                 for (int i = 1; i < 10; i++) {
48                         printf_safe("[A] About to join on thread %d\n", i);
49                         pthread_join(my_threads[i], &my_retvals[i]);
50                         printf_safe("[A] Successfully joined on thread %d (retval: %p)\n", i,
51                                     my_retvals[i]);
52                 }
53         }
54
55         printf_safe("[A] About to create thread 1\n");
56         pthread_create(&t1, NULL, &thread, NULL);
57         printf_safe("[A] About to create thread 2\n");
58         pthread_create(&t2, NULL, &thread, NULL);
59         printf_safe("About to create thread 3\n");
60         pthread_create(&t3, NULL, &thread, NULL);
61
62         printf_safe("[A] Vcore0 spinning\n");
63         printf_safe("[A] About to join on thread 1\n");
64         pthread_join(t1, &retval1);
65         printf_safe("[A] Successfully joined on thread 1 (retval: %p)\n", retval1);
66         printf_safe("[A] About to join on thread 2\n");
67         pthread_join(t2, &retval2);
68         printf_safe("[A] Successfully joined on thread 2 (retval: %p)\n", retval2);
69         printf_safe("About to join on thread 3\n");
70         pthread_join(t3, NULL);
71         while(1);
72