线程分离

pthread_detach函数

实现线程分离

       int pthread_detach(pthread_t thread);      成功:0;失败:错误号

       线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。

       进程若有该机制,将不会产生僵尸进程。僵尸进程的产生主要由于进程死后,大部分资源被释放,一点残留资源仍存于系统中,导致内核认为该进程仍存在。

       也可使用 pthread_create函数参2(线程属性)来设置线程分离。

【练习】:使用pthread_detach函数实现线程分离                                                                      【pthrd_detach.c】

一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL错误。也就是说,如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。

/***
detach.c
***/
#include<unistd.h>
#include<string.h>
#include<pthread.h>
#include<stdio.h>void *tfn(void *arg)
{int n = 3;while(n--){printf("thread count %d\n",n);sleep(1);}pthread_exit((void*)1);
}int main()
{pthread_t tid;void* tret;int err;pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);pthread_create(&tid,&attr,tfn,NULL);while(1){err = pthread_join(tid,&tret);printf("------------------- err = %d\n",err);if(0 != err){fprintf(stderr,"thread_join error : %s\n",strerror(err));}else{fprintf(stderr,"thread exit code %d\n",(int)tret);}sleep(1);}return 0;
}

运行结果:

ubuntu1604@ubuntu:~/wangqinghe/linux/20190819$ ./detach

------------------- err = 22

thread_join error : Invalid argument

thread count 2

------------------- err = 22

thread_join error : Invalid argument

thread count 1

------------------- err = 22

thread_join error : Invalid argument

thread count 0

------------------- err = 22

thread_join error : Invalid argument

------------------- err = 22

thread_join error : Invalid argument

------------------- err = 22

thread_join error : Invalid argument

------------------- err = 22

thread_join error : Invalid argument

^C

pthread_cancel函数

杀死(取消)线程                  其作用,对应进程中 kill() 函数。

       int pthread_cancel(pthread_t thread); 成功:0;失败:错误号

       【注意】:线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。

       类似于玩游戏存档,必须到达指定的场所(存档点,如:客栈、仓库、城里等)才能存储进度。杀死线程也不是立刻就能完成,必须要到达取消点。

       取消点:是线程检查是否被取消,并按请求进行动作的一个位置。通常是一些系统调用creat,open,pause,close,read,write..... 执行命令man 7 pthreads可以查看具备这些取消点的系统调用列表。也可参阅 APUE.12.7 取消选项小节。

可粗略认为一个系统调用(进入内核)即为一个取消点。如线程中没有取消点,可以通过调用pthreestcancel函数自行设置一个取消点。

被取消的线程,   退出值定义在Linux的pthread库中。常数PTHREAD_CANCELED的值是-1。可在头文件pthread.h中找到它的定义:#define PTHREAD_CANCELED ((void *) -1)。因此当我们对一个已经被取消的线程使用pthread_join回收时,得到的返回值为-1。

【练习】:终止线程的三种方法。注意“取消点”的概念。                                                              【pthrd_endof3.c】

终止线程方式

总结:终止某个线程而不终止整个进程,有三种方法:

  1. 从线程主函数return。这种方法对主控线程不适用,从main函数return相当于调用exit。
  2. 一个线程可以调用pthread_cancel终止同一进程中的另一个线程。
  3. 线程可以调用pthread_exit终止自己
/***
pthread_endof3.c
***/#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>void *tfn1(void *arg)
{printf("thread 1 returning\n");return (void *)111; 
}void *tfn2(void *arg)
{printf("thread 2 exiting\n");pthread_exit((void *)222);
}void *tfn3(void *arg)
{while (1) {//printf("thread 3: I'm going to die in 3 seconds ...\n");//sleep(1);
pthread_testcancel();    //自己添加取消点*/
    }return (void *)666;
}int main(void)
{pthread_t tid;void *tret = NULL;pthread_create(&tid, NULL, tfn1, NULL);pthread_join(tid, &tret);printf("thread 1 exit code = %d\n\n", (int)tret);pthread_create(&tid, NULL, tfn2, NULL);pthread_join(tid, &tret);printf("thread 2 exit code = %d\n\n", (int)tret);pthread_create(&tid, NULL, tfn3, NULL);sleep(3);pthread_cancel(tid);pthread_join(tid, &tret);printf("thread 3 exit code = %d\n", (int)tret);return 0;
}

ubuntu1604@ubuntu:~/wangqinghe/linux/20190819$ ./pthread_endof3

thread 1 returning

thread 1 exit code = 111

 

thread 2 exiting

thread 2 exit code = 222

 

thread 3 exit code = -1

 

转载于:https://www.cnblogs.com/wanghao-boke/p/11389738.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/384862.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

线程知识点

控制原语对比 进程 线程 fork pthread_create exit pthread_exit wait pthread_join kill pthread_cancel getpid pthread_self 命名空间 线程属性 本节作为指引性介绍&…

读写锁

读写锁 与互斥量类似&#xff0c;但读写锁允许更高的并行性。其特性为&#xff1a;写独占&#xff0c;读共享。 读写锁状态&#xff1a; 一把读写锁具备三种状态&#xff1a; 1. 读模式下加锁状态 (读锁) 2. 写模式下加锁状态 (写锁) 3. 不加锁状态 读写锁特性&#xff1a; 读…

条件变量

条件变量&#xff1a; 条件变量本身不是锁&#xff01;但它也可以造成线程阻塞。通常与互斥锁配合使用。给多线程提供一个会合的场所。 主要应用函数&#xff1a; pthread_cond_init函数 pthread_cond_destroy函数 pthread_cond_wait函数 pthread_cond_timedwait函数 pthread_c…

文件锁

借助 fcntl函数来实现锁机制。 操作文件的进程没有获得锁时&#xff0c;可以打开&#xff0c;但无法执行read、write操作。 fcntl函数&#xff1a; 获取、设置文件访问控制属性。 int fcntl(int fd, int cmd, ... /* arg */ ); 参2&#xff1a; F_SETLK (struct flock *) 设置…

进程间同步

互斥量mutex 进程间也可以使用互斥锁&#xff0c;来达到同步的目的。但应在pthread_mutex_init初始化之前&#xff0c;修改其属性为进程间共享。mutex的属性修改函数主要有以下几个。 主要应用函数&#xff1a; pthread_mutexattr_t mattr 类型&#xff1a; 用于定义…

Python3字符串

字符串是Python中最常用的数据类型&#xff0c;可以使用单引号或双引号来创建字符串 创建字符串很简单&#xff0c;为变量分配一个值即可。 val1 ‘hello world’ var2 “Runoob” Python访问字符串的值 Python不支持单字符类型&#xff0c;单字符在Python中也是作为 一个字符…

服务器客户端编程

server 下面通过最简单的客户端/服务器程序的实例来学习socket API。 server.c的作用是从客户端读字符&#xff0c;然后将每个字符转换为大写并回送给客户端。 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #incl…

Python3元组

Python的元组与列表相似&#xff0c;不同之处在于元组的元素不能修改 元组使用小括号&#xff0c;列表使用方括号 元组创建很简单&#xff0c;只需要在括号中添加元素&#xff0c;并使用逗号隔开即可。 创建空元组 tup1 (); tup2 (1,) 元组只包含一个元素时&#xff0c;需要在…

Python3字典

字典是另一种可变容器模型&#xff0c;可存储任意类型的对象。 字典的每个键值(key>value)对用冒号分隔&#xff0c;每个对之间用逗号分隔&#xff0c;整个字典包括在花括号里&#xff0c;格式如下 d {key1 : value,key2 : value2} 键必须是唯一&#xff0c;但值则不必。 值…

线程回收

pthread_join函数 阻塞等待线程退出&#xff0c;获取线程退出状态 其作用&#xff0c;对应进程中 waitpid() 函数。 int pthread_join(pthread_t thread, void **retval); 成功&#xff1a;0&#xff1b;失败&#xff1a;错误号 参数&#xff1a;thread&#xff1a;线…

Python3数字

Python3数字数据类型用于存储数值。 数据类型是不允许改变的&#xff0c;这就意味着&#xff0c;如果改变数字数据类型的值&#xff0c;将重新分配内存空间。 Python支持三种不同不同的数值类型&#xff1a; 整型&#xff08;int&#xff09;&#xff1a;通常是被称为整型或整数…

多进程服务器

注意&#xff1a;包含了“wrap.c” 和“wrap.h”文件在上篇博客中 /*** server.c ***/ #include<stdio.h> #include<string.h> #include<netinet/in.h> #include<arpa/inet.h> #include<signal.h> #include<sys/wait.h> #include<ctype…

服务器之select

select select能监听的文件描述符个数受限于FD_SETSIZE,一般为1024&#xff0c;单纯改变进程打开的文件描述符个数并不能改变select监听文件个数解决1024以下客户端时使用select是很合适的&#xff0c;但如果链接客户端过多&#xff0c;select采用的是轮询模型&#xff0c;会大…

服务器之poll

poll服务器方法采用将监听端口用数组存放起来&#xff0c;这样就不需要轮询的监听整个文件描述符了 #include <poll.h> int poll(struct pollfd *fds, nfds_t nfds, int timeout);struct pollfd {int fd; /* 文件描述符 */short events; /* 监控的事件 */short revents; …

Mysql数据库简单使用(二)

Mysql导入.sql文件 进入数据库&#xff08;要导入的数据库&#xff09;数据库中有要导入.sql文件名的数据库&#xff0c;没有则新建。source 路径文件名souce /home/robot/csql.sql 数据库文件.sql文件放在/home/robot目录下 按照时间删除数据库数据 DELETE FROM 表名 WHERE 时…

Python3集合

集合&#xff08;set&#xff09;是一个无序的不重复元素序列。 可以使用大括号{ } 或set&#xff08;&#xff09;函数来创建集合&#xff0c;注意&#xff1a;创建一个空集合必须用set(),{ }是用来创建一个空字典的。 创建格式&#xff1a; param {value01,value02,…} set(…

Python3条件判断

if语句&#xff1a; Python中if语句的一般形式如下&#xff1a; if condition_1:statement_block_1 elif condition_2:statement_block_2 else:statement_block_3 if语句关键词&#xff1a; if – elif – else 注意&#xff1a; 每个条件后面要使用冒号:使用缩进来划分语句块&…

Python3循环

Python中while语句的一般形式&#xff1a; while 判断条件: 语句 同样需要注意冒号和缩进&#xff0c;另外在Python中没有do…while循环 下面的实例计算1到100总和 ##calc.py n 100sum 0 counter 1 while counter < n:sum sum countercounter 1print("total from…

Python3迭代器和生成器

迭代器 迭代是Python最强大的功能之一&#xff0c;是访问元素集合的一种方法。 迭代器是一个可以记住遍历的位置的对象。 迭代器对象从集合的第一个元素开始访问&#xff0c;直到所有的元素被访问完结束&#xff0c;迭代器只能向前不会后退。 迭代器有两个基本方法&#xff0c;…

Pythton3实例

计算1-100之和 #add.py n 0 sum 0 for n in range(0,101):sum n print(sum) 实现99乘法法则 #mul.py i 1 while i < 9:j 1while j < i:mut j*iprint("%d * %d %d"%(j,i,mut),end" ")j 1print(" ")i 1 运算结果: robotubuntu:~/wa…