pthread_cancel pthread_testcancel测试

8 篇文章 0 订阅

pthread_cancel用于取消一个线程,但被取消的线程要有取消点,才能被取消。

pthread_testcancel用于设置取消点

 

/**
 * Created by fangruibin
 * 测试取消线程操作
 */

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

pthread_mutex_t m_mutex;


//清理函数
void cleanProc(void* arg)
{
  pthread_t tid = pthread_self();
  printf("thread %lx was canceled\n", tid);
}

//线程函数
void* threadFunc(void* p)
{
  //设置可取消
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);

  //设置线程清理回调函数,如果线程是被cancel的,而不是自然结束的,那么回调函数会被执行
  pthread_cleanup_push(cleanProc, NULL);

  printf("thread %lx is running..\n", pthread_self());
  while (1)
  {
    //设置cancelation point
    pthread_testcancel();
    sleep(1);
    pthread_testcancel();
  }

  //取消线程清理回调函数,如果线程是自然结束的,那么回调函数是不会被执行的,需要把它取消掉
  pthread_cleanup_pop(0);

  printf("thread %lx exit normally\n", pthread_self());
  return NULL;
}

int main()
{
  //初始化线程
  pthread_t hThread;
  if (pthread_create(&hThread, NULL, &threadFunc, NULL) != 0)
  {
    printf("create thread failed\n");
    return -1;
  }

  sleep(5);
  pthread_cancel(hThread); //取消线程

  pthread_join(hThread, NULL);
  sleep(1);
  printf("main exit\n");

  return 0;
}


运行结果如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值