(四)linux线程编程学习笔记——线程分离

(四)linux线程编程学习笔记——线程分离

函数原型

int pthread_detach(pthread_t thread);

默认情况下,主线程退出会释放子线程资源,分离后,就不用释放子线程资源了,为什么要分离呢?如果不分离,主线程回收子线程就需要调用pthread_join,但是pthrea_join是阻塞函数,主线程执行到该处时就不会往下执行了,分离后,资源回收变成子线程自己的事情了,主线程不负责回收子线程资源,各干各的事,相当于给主线程减负了。但是必须明确,即使分离了,主线程结束后,子线程也是会结束的。

1 #include

2 #include

3 #include

4 #include

5 struct Test{

6 int num;

7 int age;

8 };

9

10 struct Test t;

11 void* callback(void* arg){

12 printf("子线程id:%ld\n",pthread_self());

13 struct Test* t=(struct Test*)arg;

14 t->num=100;

15 t->age=30;

16 pthread_exit(&t);

17 return NULL;

18 };

19 int main(){

20 pthread_t tid;

21 struct Test t;

22 pthread_create(&tid,NULL,callback,&t);

23 printf("主线程id:%ld\n ",pthread_self());

24 pthread_detach(tid);

25 pthread_exit(NULL);

26 return 0;

27 }

相关推荐

道友请留步哪个种族强
bat365app手机版下载

道友请留步哪个种族强

📅 08-04 👁️ 7263
内马尔受伤报销,累计缺阵超600天!世界杯梦想破灭,或将提前退役
微信很卡是怎么回事
365足球直播无插件高清

微信很卡是怎么回事

📅 08-23 👁️ 8463