zoukankan      html  css  js  c++  java
  • 线程取消

    一个线程可以对另一个线程提出取消申请,即线程被动终止的一种情况。向某个线程提出取消申请的接口:

    #include <pthread.h>
    int pthread_cancel(pthread_t thread);

    如果一个线程因响应pthread_cancel而终止的,那么连接该线程时,将得到PTHREAD_CANCELED返回值。

    向线程提出取消申请,与线程真正发生终止之间,是异步的。即向线程发出取消申请,被申请线程不一定会马上终止,而是等到某个可以发生终止的时机了才终止。可以发生终止的时机,是指当线程调用某些函数时,会响应取消请求,这些函数也称为线程的取消点。 常见的线程取消点有:

    实例:

    /*
    *thread_cancel.c
    */
    #include<stdio.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<errno.h>
    
    #define handle_error_en(en, msg) 
        do {errno = en; perror(msg); exit(EXIT_FAILURE) ;} while(0)
    
    static void *thread_routine(void *arg)
    {
        int j;
        printf("New thread started
    ");    //这里又可能是一个线程取消点
        for (j = 1; ; j++)
        {
            printf("Loop %d
    ", j);    //这里也可能是一个线程取消点
            sleep(1);    //这里也可能是一个线程取消点
        }
        
        //程序执行流程时无法到达这里
        return NULL;
    }
    
    int main()
    {
        pthread_t thr;
        int s;
        void *res;
        s = pthread_create(&thr, NULL, thread_routine, NULL);
        if (0 != s)
        {
            handle_error_en(s, "pthread_create");
        }
    
        sleep(3);
        s = pthread_cancel(thr);
        if (0 != s)
        {
            handle_error_en(s, "pthread_cancel");
        }
    
        //等待线程退出
        s = pthread_join(thr, &res);
        if (0 != s)
        {
            handle_error_en(s, "pthread_join");
        }
    
        //判断新线程终止是否是相应取消而终止的
        if (res == PTHREAD_CANCELED)
        {
            printf("Thread was canceled
    ");
        }
        else
        {
            printf("Thread was not canceled (should not happen!)
    A;");
        }
    
        return 0;
    }

     

    运行结果:

  • 相关阅读:
    执行chmod -R 777 / 补救
    kill详解
    find详解
    htop详解
    C#正则表达式经典分类整理集合手册
    C# 正则表达式大全
    各种新主流.net混淆加密软件对比
    string format double
    System.Timers.Timer
    System.Threading.Timer
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11975742.html
Copyright © 2011-2022 走看看