linux_线程分离pthread_detach函数-线程取消pthread_cancel函数-线程相等pthread_equal函数

接上一篇:linux_线程基础函数-pthread_self函数-pthread_create函数-pthread_exit函数-pthread_join函数

  本次来分享怎样让线程分离、线程取消、线程相等,也就是一些函数的调用,话不多说,上菜:

此博主在CSDN发布的文章目录:我的CSDN目录,作为博主在CSDN上发布的文章类型导读

1.pthread_detach函数

函数作用:
  实现线程分离。
头文件:
  #include <pthread.h>
函数原型:
  int pthread_detach(pthread_t thread);
函数参数:
  thread:需要分离的线程ID
返回值:
  成功:0;
  失败:错误号。
注意:
  ①线程分离状态:指定该状态,线程主动与主控线程断开关系。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。
  ②不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL错误。也就是说,如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。
  一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。
但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL错误。
  也就是说,如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。

2.pthread_cancel函数

函数作用:
  杀死(取消)线程。
头文件:
  #include <pthread.h>
函数原型:
  int pthread_cancel(pthread_t thread);
函数参数:
  thread:线程ID。
返回值:
  成功:0;
  失败:错误号。
注意:
  可通过pthread_testcancel()函数设置一个取消点。
  线程的取消并不是实时的,而有一定的延时。需要等待线程到达某个取消点(检查点)。
  取消点:是线程检查是否被取消,并按请求进行动作的一个位置。
  通常是一些系统调用creat,open,pause,close,read,write… 执行命令man 7 pthreads可以查看具备这些取消点的系统调用列表。
  可粗略认为一个系统调用(进入内核)即为一个取消点。如线程中没有取消点,可以通过调用pthreestcancel函数自行设置一个取消点。
  被取消的线程,退出值定义在Linux的pthread库中。常数PTHREAD_CANCELED的值是-1。可在头文件pthread.h中找到它的定义:#define PTHREAD_CANCELED ((void *) -1)。因此当我们对一个已经被取消的线程使用pthread_join回收时,得到的返回值为-1。

2.1.终止线程方式总结

终止某个线程而不终止整个进程,有三种方法:
  1、从线程主函数return。这种方法对主控线程不适用,从main函数return相当于调用exit。
  2、一个线程可以调用pthread_cancel终止同一进程中的另一个线程。
  3、线程可以调用pthread_exit终止自己。

3.pthread_equal函数

函数作用:
  比较两个线程ID是否相等。
头文件:
  #include <pthread.h>
函数原型:
  int pthread_equal(pthread_t t1, pthread_t t2);
函数参数:
  t1:需要比较的线程号1;
  t2:需要比较的线程号2;
返回值:
  返回非0:两个线程相等。
  返回0:表示其他。

4.例子

4.1.pthread_detach函数调用-①设置线程分离-②通过属性设置-通过函数设置

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
//线程回调函数
void *tfn(void *arg)
{
    
    
	int n = 5;
    //子线程计数
	while (n--) {
    
    
		printf("thread count %d\n", n);
		sleep(1);
	}
    pthread_exit((void *)1);//线程退出
}

int main(void)
{
    
    
	pthread_t tid;
	void *tret = NULL;
	int err = -1;

#if 0
    /*通过线程属性来设置游离态*/
	pthread_attr_t attr;			
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr,	PTHREAD_CREATE_DETACHED);//设置线程分离状态
	pthread_create(&tid, &attr, tfn, NULL);

#else
    /*通过pthread_detach函数设置*/
	pthread_create(&tid, NULL, tfn, NULL);
	pthread_detach(tid);         //让线程分离  ----自动退出,无系统残留资源

#endif

	while (1) {
    
    
		err = pthread_join(tid, &tret);
        printf("-------------err= %d\n", err);
		if (err != 0)
        {
    
    
            fprintf(stderr, "thread_join error: %s\n", strerror(err));
        }
		else
			fprintf(stderr, "thread exit code %d\n", (int)tret);
		sleep(1);
	}

	return 0;
}

  以上就是本次的分享了,希望对大家有所帮助,欢迎关注博主一起学习更多的新知识!

猜你喜欢

转载自blog.csdn.net/qq_44177918/article/details/130446569