关于thread-fork/data细节实验确认(十一)
来源:互联网 发布:word判断矩阵 编辑:程序博客网 时间:2024/05/22 08:22
NOTE : 前一篇理论部分戳我
一:题目
请确定是否线程中
key
所关联的数据只有线程自身能够访问?在线程中fork
之后的程序执行流是?
二:审题
解决上面两个疑问,除了百度google等伸手的手段,还有一种就是做实验验证,设计一段代码能合理的解决上面两个疑问。在另一个不绑定key
和thread-data
的线程中获取key
所关联的数据,并在线程中执行fork,观察程序输出。
三:代码展示
[root@localhost dhuang]# vim 12_3.c#include <stdio.h>#include <err.h>#include <string.h>#include <pthread.h>#include <stdlib.h>#include <unistd.h>typedef struct {char * a ;char *b;} CHAR;static pthread_key_t key;static pthread_once_t init_done = PTHREAD_ONCE_INIT;void thread_init(void){ pthread_key_create(&key, free);}void * thr_fn(void *arg){ pid_t pid; CHAR * buffer; if((buffer=malloc(sizeof(CHAR))) == NULL) errx(1,"error in malloc\n"); pthread_once(&init_done, thread_init); if((buffer->a=malloc(10)) == NULL) errx(1,"error in malloc\n"); strncpy(buffer->a,"hello",6); if((buffer->b=malloc(3)) == NULL) errx(1,"error in malloc\n"); strncpy(buffer->b,"hi",3); pthread_setspecific(key,buffer->a); printf("thread :%s,%s\n",buffer->a,buffer->b); if((pid=fork())<0) errx(1,"error in fork\n"); if(pid==0) printf("current process is child\n"); else return((void *)buffer);}int main (void){ int err; pthread_t tid; CHAR * buffer; err=pthread_create(&tid,NULL,thr_fn,NULL); if(err!=0) errx(1, "can’t create thread\n"); if(pthread_getspecific(key) == NULL) printf("It's true that the key is only valid to it's own thread\n"); pthread_join(tid,(void **)&buffer); sleep(20); printf("%s\n",buffer->a); printf("%s\n",buffer->b); return 0; }
四:结果分析
[root@localhost dhuang]# ./12_3 It's true that the key is only valid to it's own threadthread :hello,hicurrent process is childhi[root@localhost dhuang]#
第一行打印信息和最后printf("%s\n",buffer->a);
没有输出 和buffer->b
的正常输出形成了交叉对比反映了第一个问题,只有和绑定key
的thread
才能访问thread
相关的数据。然后current process is child
反映了子线程fork
之后的子进程执行流仅仅到该子线程自身函数结束。
笔者读英文版APUE的方式,已经很认真仔细了,针对众多细节进行验证。当然不必多言,但行好事。
NOTE: 如有疑问,请及时指正。
阅读全文