zoukankan      html  css  js  c++  java
  • linux下pthread_cancel无法取消线程的原因

    一个线程能够调用pthread_cancel终止同一进程中的还有一个线程,可是值得强调的是:同一进程的线程间,pthread_cancel向还有一线程发终止信号。系统并不会立即关闭被取消线程,仅仅有在被取消线程下次系统调用时,才会真正结束线程。或调用pthread_testcancel,让内核去检測是否须要取消当前线程。被取消的线程,退出值。定义在Linux的pthread库中常数PTHREAD_CANCELED的值是-1。

    #include <pthread.h>
    
    int pthread_cancel(pthread_t thread);
    

    看以下程序:

    #include<stdio.h>
    #include<stdlib.h>
    #include <pthread.h>
    void *thread_fun(void *arg)
    {
    	int i=1;
    	printf("thread start 
    ");
    	while(1)
    	{
    		i++;
    	}
    	return (void *)0;
    }
    int main()
    {
    	void *ret=NULL;
    	int iret=0;
    	pthread_t tid;
    	pthread_create(&tid,NULL,thread_fun,NULL);
    	sleep(1);
    	
    	pthread_cancel(tid);//取消线程
    	pthread_join(tid, &ret);
    	printf("thread 3 exit code %d
    ", (int)ret);
    	
    	return 0;
    	
    }
    


    会发现程序再一直执行。线程无法被取消,究其原因pthread_cancel向还有一线程发终止信号。系统并不会立即关闭被取消线程,仅仅有在被取消线程下次系统调用时,才会真正结束线程。

    假设线程里面没有执行系统调用。能够使用pthread_testcancel解决。

    #include<stdio.h>
    #include<stdlib.h>
    #include <pthread.h>
    void *thread_fun(void *arg)
    {
    	int i=1;
    	printf("thread start 
    ");
    	while(1)
    	{
    		i++;
    		pthread_testcancel();
    	}
    	return (void *)0;
    }
    int main()
    {
    	void *ret=NULL;
    	int iret=0;
    	pthread_t tid;
    	pthread_create(&tid,NULL,thread_fun,NULL);
    	sleep(1);
    	
    	pthread_cancel(tid);//取消线程
    	pthread_join(tid, &ret);
    	printf("thread 3 exit code %d
    ", (int)ret);
    	
    	return 0;
    	
    }
    


  • 相关阅读:
    Linux环境下MySQL报Table 'xxx' doesn't exist错误解决方法
    mysql主主复制(双主复制)配置步骤
    MHA安装手记
    MySQL MHA配置
    innobackupex 还原和备份实例
    scp命令
    给想进入餐饮业新手一些建议
    mysql mha 主从自动切换 高可用
    mysql innobackupex xtrabackup 大数据量 备份 还原
    MySQL主从复制、半同步复制和主主复制概述
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6984516.html
Copyright © 2011-2022 走看看