Pthread create, join, and exit
[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         printf_safe("[A] pthread %d on vcore %d\n", pthread_self()->id, vcore_id());
21         return (void*)(pthread_self()->id);
22 }
23
24 int main(int argc, char** argv) 
25 {
26         void *retval1 = 0;
27         void *retval2 = 0;
28
29         while (1) {
30                 for (int i = 1; i < 10; i++) {
31                         printf_safe("[A] About to create thread %d\n", i);
32                         pthread_create(&my_threads[i], NULL, &thread, NULL);
33                 }
34                 for (int i = 1; i < 10; i++) {
35                         printf_safe("[A] About to join on thread %d\n", i);
36                         pthread_join(my_threads[i], &my_retvals[i]);
37                         printf_safe("[A] Successfully joined on thread %d (retval: %p)\n", i,
38                                     my_retvals[i]);
39                 }
40         }
41
42         printf_safe("[A] About to create thread 1\n");
43         pthread_create(&t1, NULL, &thread, NULL);
44         printf_safe("[A] About to create thread 2\n");
45         pthread_create(&t2, NULL, &thread, NULL);
46         printf_safe("About to create thread 3\n");
47         pthread_create(&t3, NULL, &thread, NULL);
48
49         printf_safe("[A] Vcore0 spinning\n");
50         printf_safe("[A] About to join on thread 1\n");
51         pthread_join(t1, &retval1);
52         printf_safe("[A] Successfully joined on thread 1 (retval: %p)\n", retval1);
53         printf_safe("[A] About to join on thread 2\n");
54         pthread_join(t2, &retval2);
55         printf_safe("[A] Successfully joined on thread 2 (retval: %p)\n", retval2);
56         printf_safe("About to join on thread 3\n");
57         pthread_join(t3, NULL);
58         while(1);
59