pthread最简单的多线程编程-001 和pthread最简单的多线程编程-002 代码里pthread_exit 和pthread_join接受的参数都是NULL,如果不传NULL,应该如何编码实现呢,而实现之后对我们有什么帮助吗?这就是本文要说的重点:更可靠的终止线程。
1 更可靠地终止线程
更可靠的终止线程意思是在子线程调用pthread_exit 终止自己后,能够让主线程得到子线程的退出状态,然后主线程在pthread_join成功返回后,得到子线程退出状态,最后主线程根据不同的退出状态,可能需要做不同的收尾处理工作。
2 关键代码
主线程
/* 主线程为每个子线程传递独立的专有参数 thread_arg */
int *thread_arg = malloc(sizeof(int));
pthread_create(&threads[i], NULL, hello_world_thread, (void*)thread_arg);
/* 主线程等待子线程退出,并获取退出状态 */
pthread_join(threads[i], &status);
if(status)
{
if(memcmp(status,"i have free arg's memory",strlen("i have free arg's memory"))==0)
{
printf("--join %d: I'm freeing status's memory %p\n",i, status);
}
else
{
printf("--join %d: I'm freeing arg's memory %p\n",i,status);
}
free(status);
}
子线程
if(id%2 ==0)
{
/* 如果id被2整除,将arg指代的内存释放,并分配新的内存存放status返回给pthread_join */
char *status = malloc(strlen("i have free arg's memory")+1);
if(status)
{
memset(status,0x00,strlen("i have free arg's memory")+1);
memcpy(status,"i have free arg's memory",strlen("i have free arg's memory"));
printf("thread %d: %s %p, but malloc %p\n",id,status, arg,status);
free(arg);
pthread_exit((void*)status);
}
}
/* 如果id不能被2整除,或者分配新的内存status失败,将arg作为status返回给pthread_join */
printf("thread %d: wait pthread_join free arg's memory %p\n",id,arg);
pthread_exit(arg);
完整代码,请下载 hello_join_exit.c
3 运行结果
从运行结果分析
线程0 红色圈起的部分,专有参数指针 000E1530,在线程内部被free了,然后malloc了一个新内存status 000E11800,存放了字符串“i have free arg's memory”,主线程在join后free了000E11800内存。
线程1 ,专有参数指针 000E1570,在线程内部没有被free,而是作为pthread_exit参数,等到主线程join后才free了000E1570这部分内存。