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
|
// APUE example 11-4
// lcl 20190314
/******************************************
[root@f3c6f9f95723 ch11]# ./exit_thread_err
structure at 0x7f33a3ce7f00
foo.a = 1
foo.b = 2
foo.c = 3
foo.d = 4
parent create a second thread:
thread 2: ID is 139859768280832
structure at 0x7ffebf271120
foo.a = -1546748160
foo.b = 32563
foo.c = -1087952529
foo.d = 32766
******************************************/
#include "../myapue.h"
#include <pthread.h>
struct foo {
int a, b, c, d;
};
void printfoo(const char *s, const struct foo *fp)
{
printf("%",s);
printf(" structure at 0x%lx\n", (unsigned long)fp);
printf(" foo.a = %d\n",fp->a);
printf(" foo.b = %d\n",fp->b);
printf(" foo.c = %d\n",fp->c);
printf(" foo.d = %d\n",fp->d);
}
void *thr_fn1(void *arg)
{
struct foo foo1 = {1,2,3,4};
printfoo("thread 1:\n", &foo1);
pthread_exit((void*)&foo1);
}
void *thr_fn2(void *arg)
{
printf("thread 2: ID is %lu\n",(unsigned long)pthread_self());
pthread_exit((void *)0);
}
int main(void)
{
int err;
pthread_t tid1,tid2;
struct foo *fp;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
if(err != 0)
printf("err %d, can't create thread 1\n",err);
err = pthread_join(tid1, (void*)fp);
if (err != 0)
printf("err %d, can't join with thread1\n",err);
sleep(1);
printf("parent create a second thread:\n");
err = pthread_create(&tid2, NULL, thr_fn2, NULL);
if (err != 0)
printf("err %d, can't create thread 2\n",err);
sleep(1);
printfoo("parent:\n",fp);
exit(0);
}
|