Linux下多线程编程之——线程分离

一、线程分离属性

  线程通常分为可合并和不可合并线程,前者不能被其他线程(包括主线程)收回资源并杀死,其资源在其终止后由系统释放;后者则可以被主线程杀死或进行资源回收,甚至是资源是被强制回收的,主线程可以全程监控线程的运行状态。

二、pthread_attr_setdetachstate函数,该函数可以设置线程合并属性:

  1、第一个参数:pthread_attr_t结构,它存储了线程属性

  2、第二个参数:常量PTHREAD_CREATE_DETACHED,表示该线程是不可合并线程;常量PTHREAD_CREATE_JOINABLE,表示该线程是可合并线程

三、代码test7_3.c

1 //This is c program code!                                                                                                                      
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文档信息: *** :~/test7_3.c
 4   * 版权声明: *** :(魎魍魅魑)MIT
 5   * 联络信箱: *** :guochaoxxl@163.com
 6   * 创建时间: *** :2020年11月17日的下午04:53
 7   * 文档用途: *** :数据结构与算法分析-c语言描述
 8   * 作者信息: *** :guochaoxxl(http://cnblogs.com/guochaoxxl)
 9   * 修订时间: *** :2020年第46周 11月17日 星期二 下午04:53 (第322天)
10   * 文件描述: *** :自行添加
11  * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/
12 #include <stdio.h>
13 #include <pthread.h>
14 
15 void *myComadd(void *iData){
16     int sum = 0;
17     int *data = (int *)(iData);
18 
19     for(int i = 1; i < *data + 1; i++){
20         sum += i;
21     }
22     printf("add result: %d
", sum);
23 }
24 
25 void *myCommul(void *iData){
26     int sum = 1;
27     int *data = (int *)(iData);
28 
29     for(int i = 1; i < *data + 1; i++){
30         sum *= i;
31     }
32     printf("mul result: %d
", sum);
33 }
34 
35 int main(int argc, char **argv)
36 {
37     pthread_t threadA;
38     pthread_t threadB;
39     pthread_t threadC;
40     pthread_attr_t detachedatrr;
41     int n = 9;
42 
43     pthread_create(&threadA, NULL, myComadd, &n);
44     pthread_create(&threadB, NULL, myCommul, &n);
45 
46     pthread_attr_init(&detachedatrr);
47     pthread_attr_setdetachstate(&detachedatrr, PTHREAD_CREATE_DETACHED);
48     pthread_create(&threadC, &detachedatrr, myCommul, &n);
49     pthread_join(threadA, NULL);
50 
51     return 0;
52 }

  1、主线程创建了2个可合并线程threadA和threadB,不可合并线程threadC

  2、线程threadA完成累加计算,线程threadB完成相乘计算,线程threadC完成相乘计算

  3、动态改变了线程threadB的不可合并性,变成了不可合并线程

  4、对可合并线程,主线程通过pthread_join()函数实现对线程threadA状态的监控,等待线程结束后,释放其占用的资源

  5、而threadB和threadC不可合并线程来说,运行完毕后,由系统接管其占用的资源

原文地址:https://www.cnblogs.com/guochaoxxl/p/14002463.html