-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpthread.c
95 lines (75 loc) · 1.75 KB
/
pthread.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
static int thread_cnt;
int safe_pthread_create(pthread_t *thread_id, const pthread_attr_t *attr,
void *(*thread_fn)(void *), void *arg) {
int rval;
rval = pthread_create(thread_id, attr, thread_fn, arg);
if (rval) {
printf("failed\n");
exit(1);
}
return rval;
}
int safe_pthread_join(pthread_t thread_id, void **retval) {
int rval;
printf("just before pthread join %lx\n", thread_id);
rval = pthread_join(thread_id, retval);
if (rval) {
printf("failed\n");
exit(1);
}
printf("pthread succeed\n");
return rval;
}
static void spawn_threads(pthread_t *id, void *(*thread_fn)(void *)) {
intptr_t i;
for (i = 0; i < thread_cnt; ++i)
safe_pthread_create(id + i, NULL, thread_fn, (void *)i);
}
static void wait_threads(pthread_t *id) {
int i;
while (true) {
void *x = malloc(0x10);
free(x);
}
for (i = 0; i < thread_cnt; ++i) {
printf("pthread join never works %d\n", i);
safe_pthread_join(id[i], NULL);
}
}
void *thread_fn_01(void *arg) {
int i;
printf("%ld stack = %p\n", (intptr_t)arg, &i);
while (true) {
void *x = malloc(0x10);
free(x);
}
return NULL;
}
static void test01(void) {
intptr_t i;
int k;
pthread_t id[thread_cnt];
int res[thread_cnt];
printf("parent stack %p\n", &k);
spawn_threads(id, thread_fn_01);
for (int i = 0; i < thread_cnt; ++i) {
printf("i=%d pthread_t[i]=%lx\n", i, id[i]);
}
wait_threads(id);
printf("all child returned\n");
}
int main(int argc, char *argv[]) {
thread_cnt = 1;
test01();
return 0;
}