取消一个线程

有时,我们想让一个线程可以要求另一个线程终止,就像给它发送一个信号一样。线程有方法可以做到这一点,与信号处理一样,线程可以被要求终止时改变其行为。

#include <pthread.h>

int pthread_cancel(pthread_t thread);

这个函数简单易懂,提供一个线程标识符,我们就可以发生请求来取消它。但在接收到取消请求的一端,事情会稍微复杂一点,不过也不是非常复杂。线程可以用pthread_setcancelstate设置自己的取消状态。

#include <pthread.h>

int pthread_setcancelstate(int state,int *oldstate);

第一个参数的取值可以是PTHREAD_CANCEL_ENABLE,这个值允许线程接收取消请求;或者是PTHREAD_CANCEL_DISABLE,它的作用是忽律取消请求。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function(void *arg);

int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;

    res = pthread_create(&a_thread,NULL,thread_function,NULL);

    if(res != 0)
    {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    
    sleep(3);
    printf("Canceling thread....\n");
    res = pthread_cancel(a_thread);
    if(res != 0)
    {
        perror("Thread cancelation failed");
        exit(EXIT_FAILURE);
    }

    printf("Waiting for thread to finish...\n");
    res = pthread_join(a_thread,&thread_result);
    if(res != 0)
    {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
 }


void *thread_function(void *arg)
{
    int i,res;
    res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
    if(res != 0)
    {
        perror("Thread pthread_setcancelstate failed");
        exit(EXIT_FAILURE);
    }

    res = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);

    if(res != 0)
    {
        perror("Thread pthread_setcanceltype failed");
        exit(EXIT_FAILURE);
    }
    printf("thread_function is running\n");
    for(i=0;i<10;i++)
    {
        printf("Thread is still running(%d)...\n",i);
        sleep(1);
     }
     pthread_exit(0);
}



./thread7

thread_function is running

Thread is still running (0)...

Thread is still running(1)...

Thread is still running(2)...

Canceling thread...

Waiting for thread to finish

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值