线程的取消pthread_cancel()函数(线程三)

一、线程取消相关函数

1pthread_cancel().线程取消函数

成功返回0,失败返回错误码。

2.pthread_setcancelstate().设置线程取消状态

成功返回0,失败返回错误码。

该函数第一个参数,有两种情况(响应和不响应取消函数),第二个参数就旧状态,一般为空。

3.pthread_setcanceltype().设置取消类型

在可取消的状态下 ,又分为立即取消和延时取消。

成功返回0,失败返回错误码。

该函数第一个参数:有两个种状态立即取消延时取消,第二个参数就旧状态,一般为空

扩展:延时取消涉及到一个取消点(cancel point),在书册中man pthreads

二:代码

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>

void* thread_fun(void * arg)
{
    printf("i am new thread ...\n");
//pthread_setcancelstate(state, *oldstate);
    int cancel_state;
    cancel_state = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    if(cancel_state != 0)
    {
        printf("pthread_setpthreadstate is failed ...\n");
        return (void*)0;
    }
    //printf("i am new thread ...\n");

    sleep(3);
    printf("about to cancel.\n");
//pthread_setcancelstate(state, *oldstate);
    cancel_state = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
    if(cancel_state != 0)
    {
        printf("pthread_setcancelstate is failed ...\n");
        return (void*)0;
    }
//pthread_setcanceltype(state, *oldstate);
    int cancel_type;
    cancel_type = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);
    if (cancel_type != 0)
    {
        printf("pthread_t");
        return (void*)0;
    }
//set cancelpoint: printf();
    printf("i am first cancelpoint...\n");
    printf("i am second cancelpoint ...\n");

    return (void*)20;

}

int main(int argc , char ** argv)
{
    pthread_t  tid;
    int err ;
    void *retval;

    //creat new thread
    err = pthread_create(&tid , NULL , thread_fun, NULL);
    if(err != 0)
    {
        printf("pthread create is failed..\n");
        return 0;
    }
    printf("i  am main thread...\n");
    sleep(1);

//pthread_cancel(pthread_t tid);
    int cancel_val ;
    cancel_val = pthread_cancel(tid);
    if(cancel_val != 0)
    {
        printf("pthread cancel is failed ...\n");
        return 0;
    }

// pthread_join(pthread_t tid ,void**retval);
    int  join_val;
    join_val = pthread_join(tid,&retval);
    if(join_val != 0)
    {
        printf("pthread join is failed ...\n");
        return 0;
    }
//printf(" new thread exit coid");
    printf("the new thread exit code is %d\n",(int *)retval);
    return 0;
}


运行程序

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值