主程序访问线程的临时变量时得到的是不可好的数据,该段内存已经被收回。
源代码:
1 #include "apue.h"
2 #include <pthread.h>
3
4 struct foo{
5 int a;
6 int b;
7 int c;
8 int d;
9 };
10
11 void printfoo(const char *s,const struct foo *foop)
12 {
13 printf("In %s:",s);
14 printf("struct foo address:0x%lx\n",(unsigned long)foop);
15 printf("foo.a=%d\n",foop->a);
16 printf("foo.b=%d\n",foop->b);
17 printf("foo.c=%d\n",foop->c);
18 printf("foo.d=%d\n",foop->d);
19 }
20
21
22
23 void *thread1_func(void *arg)
24 {
25 struct foo f = {1,2,3,4};
26 printfoo("thread1",&f);
27 pthread_exit((void *) &f);
28 }
29
30 void *thread2_func(void *arg)
31 {
32 printf("In thread2");
33 pthread_exit((void *)2);
34 }
35
36 int main()
37 {
38 int err;
39 pthread_t td1,td2;
40 struct foo fp;
41 err = pthread_create(&td1,NULL,thread1_func,NULL);
42 if (0 != err)
43 err_exit(err,"thread1 create error");
44
45 err = pthread_join(td1,(void *)&fp);
46 if (0 != err)
47 err_exit(err,"join thread1 error");
48
49 sleep(1);
50 printf("Main function start to lunch thread2");
51 err = pthread_create(&td2,NULL,thread2_func,NULL);
52 if (0 != err)
53 err_exit(err,"thread2 create error");
54 sleep(1);
55 printfoo("Main function\n",&fp);
56
57 exit(0);
58
59
60 }
编译及运行结果:
./temp_value
In thread1:struct foo address:0xff07bf80
foo.a=1
foo.b=2
foo.c=3
foo.d=4
Main function start to lunch thread2In thread2In Main function
:struct foo address:0xffbfe630
foo.a=-16269440
foo.b=116
foo.c=2130640639
foo.d=-13105240