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 \n");
	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\n", (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 \n");
	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\n", (int)ret);
	
	return 0;
	
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM