1、线程属性的设置
1 /************************************************************************* 2 > File Name: pthread_attr.c 3 > Summary: 线程属性的设置---举例创建线程之时就设置线程分离 4 > Author: xuelisheng 5 > Created Time: 2018年12月17日 6 ************************************************************************/ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #include <unistd.h> 12 #include <errno.h> 13 #include <pthread.h> 14 15 void *tfn(void *arg) 16 { 17 printf("thread : pid = %d, tid = %lu\n", getpid(), pthread_self()); 18 return NULL; 19 } 20 21 22 int main() 23 { 24 pthread_t tid; 25 // 属性结构体 26 pthread_attr_t attr; 27 28 int ret = pthread_attr_init(&attr); 29 if(ret != 0){ 30 fprintf("stderr", "attr_init error:%s\n", strerror(ret)); 31 exit(1); 32 } 33 34 // 设置线程属性 35 ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 36 if(ret != 0){ 37 fprintf("stderr", " pthread_attr_setdetachstate error:%s\n", strerror(ret)); 38 exit(1); 39 } 40 //ret = pthread_create(&tid, &attr, tfn, NULL); 41 ret = pthread_create(&tid, NULL, tfn, NULL); 42 if(ret != 0){ 43 perror("pthread_create error"); 44 } 45 46 // 销毁 47 ret = pthread_attr_destroy(&attr); 48 if(ret != 0){ 49 fprintf("stderr", " pthread_attr_destroy error:%s\n", strerror(ret)); 50 exit(1); 51 } 52 53 ret = pthread_join(tid, NULL); // 使用join函数用来验证detach属性是否生效,如果生效则返回值为无效 54 if(ret != 0){ 55 fprintf("stderr", " pthread_join error:%s\n", strerror(ret)); 56 exit(1); 57 } 58 printf("main : pid = %d, tid = %lu\n", getpid(), pthread_self()); 59 pthread_exit((void *)0); 60 return 0; 61 }
运行结果:
pthread_join error : Invalid argument
关于上面的demo:
(1)上面的功能实际上可以直接通过使用pthread_detach实现,但是如果创建线程较多,则可以直接在创建线程时直接设置分离属性。
(2)随着一个进程中的线程的数量增多,进程中的栈资源均分的更少,此时可以设置线程属性,来进行堆上空间的开辟,这也是进行线程属性设置的一个应用。
2、线程使用的总结
(1)主线程退出而其他线程不退出,主线程应该调用pthread_exit。
(2)避免僵尸线程:pthread_join、pthread_detach、pthread_create指定分离属性
被join线程可能在join函数返回前就释放自己的所有内存资源,所以不应该返回被回收线程栈中的值。
(3)malloc申请的内存可以被其他线程释放(共享)。
(4)应避免在多线程模型中调用fork,除非立即exec。fork出的子进程中只有调用fork的线程存在,其他线程在子进程中均pthread_exit。
(5)信号的复杂语义很难和多线程共存,所以应避免在多线程中引入信号机制。