C++取消线程实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89071824

一 取消线程失败

1 代码

#include<stdio.h>  
#include<stdlib.h>  
#include <pthread.h>  
#include <unistd.h> //sleep
void *thfunc(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, thfunc, NULL);    // 创建线程
    sleep(1);  
          
    pthread_cancel(tid);//发送取消线程的请求
    pthread_join(tid, &ret);  //等待线程结束
    if (ret == PTHREAD_CANCELED)  //判断线程是否成功结束
        printf("thread has stopped,and exit code: %d\n", ret);  
    else
        printf("some error occured");
          
    return 0;  
          
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
thread start--------
^C

3 说明

从运行结果可以看到,程序打印thread start--------后就没反应了,我们只能按CTRL+C键来停止进程。这说明主线程虽然发送取消请求了,但并没有让子线程停止运行。因为如果停止了运行,pthread_join是会返回的,然后会打印后面的语句。

二 取消线程成功

1 代码

#include<stdio.h>  
#include<stdlib.h>  
#include <pthread.h>  
#include <unistd.h> //sleep
void *thfunc(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, thfunc, NULL);  // 创建线程
    sleep(1);  
          
    pthread_cancel(tid);//发送取消线程的请求  
    pthread_join(tid, &ret);    //等待线程结束
    if (ret == PTHREAD_CANCELED)  // 判断是否成功取消线程
        printf("thread has stopped,and exit code: %d\n", ret);  
    else
        printf("some error occured");
          
    return 0;  
          
}  

2 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
thread start--------
thread has stopped,and exit code: -1

3 说明

这个例子取消成功了,目标线程停止运行,返回pthread_join,并且得到的线程返回真正 PTHREAD_CANCELED。原因在于我们在while死循环中添加了函数pthread_testcancel,让系统每次循环都去检查一下有没有取消请求。不用pthread_testcancel也可以,可以在while循环中用sleep函数来代替,但这样会影响while的速度。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89071824