forked from 54shady/linuxc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_thread.c
More file actions
74 lines (57 loc) · 1.15 KB
/
multi_thread.c
File metadata and controls
74 lines (57 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 2
/*
* start routines functions point array
* contain all the start routines
*/
void *(*routines[NUM_THREADS])(void*);
void *start_routine1(void *args)
{
int cnt;
cnt = *(int *)args;
while (1)
{
printf("***%s, (value = %d)\n", __FUNCTION__, cnt);
sleep(cnt);
}
}
void *start_routine2(void *args)
{
int cnt;
cnt = *(int *)args;
while (1)
{
printf("###%s, (value = %d)\n", __FUNCTION__, cnt);
sleep(cnt);
}
}
int main(int argc, char *argv[])
{
int ret, i;
int values[NUM_THREADS] = {1, 2};
pthread_t tids[NUM_THREADS];
/* init the function point array */
routines[0] = start_routine1;
routines[1] = start_routine2;
for (i = 0; i < NUM_THREADS; i++)
{
ret = pthread_create(&tids[i], NULL, routines[i], &values[i]);
if (ret != 0)
{
perror("create thread error\n");
return -1;
}
/*
* shouldn't join here
* or there just one child thread running not two
*/
//pthread_join(tids[i], NULL);
}
/* joint the child threads at the end */
for (i = 0; i < NUM_THREADS; i++)
pthread_join(tids[i], NULL);
return 0;
}