函数:
int pthread_cancel(pthread_t thread);//参数:线程 ID
注意:并不是调用了 pthread_cancel,就一定能杀死进程,
必须死在“取消点”上,就是必须作一次系统调用,在不知道函数体中是否有取消点的情况下,也可以手动添加 pthread_testcancel();
举例:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
void * func (void *arg) {
while(1){
// printf("I am a thread,tid=%lu\n", pthread_self() ); //获得子线程ID
// sleep(1);
pthread_testcancel(); // 如果while内语句全部注释后,就必须自己设置取消点
}
return NULL; }
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, func, NULL); //创建子线程
printf("I am main thread, will kill %lu after 3s\n", tid);
sleep(3); //防止子线程马上被杀死
pthread_cancel(tid); //杀死线程
int ret = pthread_join(tid, NULL); //回收子进程资源
if(ret > 0){
printf("ret = %d, msg=%s\n",ret, strerror(ret)); //回收失败,输出错误号,打印错误信息
}
return 0;
}