linux 线程 线程的分离 线程取消 detach cancel

线程的分离:分离后不能进行连接

复制代码
 1 /*
 2     detach a thread
 3     int pthread_detach(pthread_t thread);
 4         - 功能:分离一个线程,被分类的线程在终止的时候,会自动释放资源返回给系统
 5             1.不能多次分离,会产生不可以预料的行为
 6             2.不能去连接(join)一个已经分离(detach)的线程,会报错
 7         - 参数:需要分离的线程的ID
 8         - 返回值:
 9             成功:0
10             失败:返回错误号
11 */
12 #include <stdio.h>
13 #include <pthread.h>
14 #include <unistd.h>
15 #include <string.h>
16 void * callback(void * arg)
17 {
18     printf("child thread id: %ld\n",pthread_self());
19     return NULL;
20 }
21 int main()
22 {
23     //创建一个子线程
24     pthread_t tid;
25     int ret = pthread_create(&tid, NULL, callback, NULL);
26     if( ret != 0)
27     {
28         char * errstr = strerror(ret);
29         printf("error1: %s\n",errstr);
30     }
31     //输出主线程和子线程ID
32     printf("tid: %ld, main thread id:%ld\n",tid, pthread_self());
33     //设置主线程分离, 子线程分离后,子线程结束时的资源就不需要主线程释放
34     ret = pthread_detach(tid);
35     if( ret != 0)
36     {
37         char * errstr = strerror(ret);
38         printf("error2: %s\n",errstr);
39     }
40     //设置分离后,对分离的子线程进行连接  pthread_join()
41     ret = pthread_join(tid,NULL);//分离后不能进行连接
42     if( ret != 0)
43     {
44         char * errstr = strerror(ret);
45         printf("error3: %s\n",errstr);//报错 Invalid argument
46     }
47     pthread_exit(NULL);
48     return 0;
49 }
复制代码

线程取消:

复制代码
 1 /*
 2     int pthread_cancle(pthread_t thread);
 3         - 功能: 取消线程(让线程终止)
 4             取消某个线程,可以终止某个线程的运行,但是并不是立刻终止,而是当子线程执行到一个取消点,线程才会终止
 5             取消点:系统规定好的一些系统调用,可以粗略的理解为从用户区到内核区的切换,这个位置称之为取消点
 6 */
 7 #include <stdio.h>
 8 #include <pthread.h>
 9 #include <unistd.h>
10 #include <string.h>
11 void * callback(void* arg)
12 {
13     printf("child thread id: %ld\n",pthread_self());
14     for(int i = 0; i < 5; i++)
15     {
16         printf("child: %d\n",i);//任一printf都可能为取消点
17     }
18     return NULL;
19 }
20 int main()
21 {
22     //创建一个子线程
23     pthread_t tid;
24     int ret = pthread_create(&tid, NULL, callback, NULL);
25     if(ret  != 0)
26     {
27         char * errstr = strerror(ret);
28         printf("error1: %s\n",errstr);
29     }
30     //取消线程
31     pthread_cancel(tid);
32     for(int i = 0; i < 5; i++)
33     {
34         printf("%d\n",i);
35     }
36     //输出主线程和子线程的ID
37     printf("tid: %ld,  main thread id: %ld\n",tid,pthread_self());
38     //退出子线程
39     pthread_exit(NULL);
40     return 0;
41 }
复制代码

posted on   廿陆  阅读(37)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示