/*0.取消线程 
  int pthread_cancel(pthread_t thread);
设置取消点
  void pthread_testcancel(void);
测试是否接收到取消请求,如果有,结束线程。
例子:*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
int a = 0;
void *thread1(void *arg)
{
         pthread_testcancel(); 这个函数非常重要要和 pthread_cancel(t1),结合起来使用;
         a = 10; 
} 
/*如果改为:
 int a = 0;
void *thread1(void *arg)
{
         a = 10;
       pthread_testcancel();
 }
运行结果:a值被修改了
main start
main end, a=10*/
int main(int argc, char *argv[])
{       
        pthread_t  t1, t2, t3;
        int ret, i;
        printf("main start\n");
        ret = pthread_create(&t1, NULL, thread1, NULL);
        pthread_cancel(t1);
        pthread_join(t1, NULL);
        sleep(3);
        printf("main end, a=%d\n", a);
      return 0;
}
/*运行结果:在取消点处程序结束,a值未该。
main start
main end, a=0*/

 

相关文章:

  • 2021-11-26
  • 2021-12-18
  • 2021-05-19
  • 2021-12-19
  • 2021-12-22
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-02
  • 2022-01-12
  • 2022-12-23
相关资源
相似解决方案