1.三种取消状态
Off                   禁用取消
Deferred           推迟取消:在下一个取消点执行取消
Asynchronous   异步取消:可以随时执行取消

int pthread_cancel(pthread_t thread)

 

2.推迟取消:在下一个取消点执行取消

Pthreads系统上的某些函数会被作为取消点,如pthread_testcancel,sleep,pthread_cond_wait等。
线程调用pthread_cancel函数后,被取消线程不会立即取消,仅仅在到达取消点时响应取消请求。

代码示例如下:

在pthread_testcancel取消点,响应线程取消请求。

#include<stdio.h>                                                                
#include<pthread.h>
#include<errno.h>
int counter;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_route(void *arg)
{
        pthread_mutex_lock(&mutex);
        for(counter=0;;counter++)
        {
                if(counter%2000==0){
                        printf("calling testcancel\n");
                        pthread_testcancel();
                }

        }
        pthread_mutex_unlock(&mutex);
}
int main(void)
{
        pthread_t tid;
        void *result;
        pthread_create(&tid,NULL,thread_route,NULL);
        sleep(1);
        printf("call cancel\n");
        pthread_cancel(tid);
        printf("call joining\n");
        pthread_join(tid,&result);
        if(result==PTHREAD_CANCELED)
        {
            printf("Thread cancelled at %d\n",counter);
        }
        else{
                printf("Thread was not canceled\n");
        }
        pthread_mutex_lock(&mutex);
        printf("main thread locked");
        pthread_mutex_unlock(&mutex);
} 
View Code

相关文章:

  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2021-06-12
  • 2021-06-01
  • 2022-01-17
  • 2021-10-31
猜你喜欢
  • 2021-07-13
  • 2021-12-06
  • 2022-12-23
  • 2021-12-19
  • 2021-07-16
  • 2022-01-13
相关资源
相似解决方案