Commit | Line | Data |
---|---|---|
0312286c DJ |
1 | #include <stdio.h> |
2 | #include <unistd.h> | |
3 | #include <stdlib.h> | |
4 | #include <pthread.h> | |
5 | ||
6 | void *thread_function(void *arg); /* Pointer to function executed by each thread */ | |
7 | ||
8 | int slow = 0; | |
9 | ||
10 | #define NUM 5 | |
11 | ||
12 | int main() { | |
13 | int res; | |
14 | pthread_t threads[NUM]; | |
15 | void *thread_result; | |
16 | int args[NUM]; | |
17 | int i; | |
18 | ||
19 | for (i = 0; i < NUM; i++) | |
20 | { | |
21 | args[i] = i; | |
22 | res = pthread_create(&threads[i], NULL, thread_function, (void *)&args[i]); | |
23 | } | |
24 | ||
25 | for (i = 0; i < NUM; i++) | |
26 | res = pthread_join(threads[i], &thread_result); | |
27 | ||
28 | printf ("Done\n"); | |
29 | ||
30 | if (slow) | |
31 | sleep (4); | |
32 | ||
33 | exit(EXIT_SUCCESS); | |
34 | } | |
35 | ||
36 | void *thread_function(void *arg) { | |
37 | int my_number = *(int *)arg; | |
38 | int rand_num; | |
39 | ||
40 | printf ("Print 1, thread %d\n", my_number); | |
41 | sleep (1); | |
42 | ||
43 | if (slow) | |
44 | { | |
45 | printf ("Print 2, thread %d\n", my_number); | |
46 | sleep (1); | |
47 | printf ("Print 3, thread %d\n", my_number); | |
48 | sleep (1); | |
49 | printf ("Print 4, thread %d\n", my_number); | |
50 | sleep (1); | |
51 | printf ("Print 5, thread %d\n", my_number); | |
52 | sleep (1); | |
53 | } | |
54 | ||
55 | printf("Bye from %d\n", my_number); | |
56 | pthread_exit(NULL); | |
57 | } | |
58 |