线程取消选项

来源:互联网 发布:sql2000 mdf恢复数据库 编辑:程序博客网 时间:2024/05/22 14:18

线程取消选项涉及以下函数运用

1.int pthread_cancel(pthread_t tid)

2.int ptnread_setcancelstate(int state, int *oldstate)

3.void pthread_testcancel(void)

4.int pthread_setcanceltype(int type, int *oldtype)

举例运用------->基于<<UNIX 环境高级编程>>例子 做的改动


#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int oldstate,oldtype;
void *
thr_fn1(void *arg)
{
 printf("thread 1 returning\n");
 return((void *)1);
}

void *
thr_fn2(void *arg)
{
       
 /*pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate);*/
 /*pthread_testcancel();*/

 /*pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);*/
       
 printf("thread 2 returning\n");

 pthread_exit((void *)2);
}

int
main(void)
{
 int   err;
 pthread_t tid1, tid2;
 void  *tret;

 err = pthread_create(&tid1, NULL, thr_fn1, NULL);
 if (err != 0)
  

                  printf("can't create thread 1: %s\n", strerror(err));
 err = pthread_create(&tid2, NULL, thr_fn2, NULL);
 if (err != 0)
  

                  printf("can't create thread 2: %s\n", strerror(err));
       if(!(pthread_cancel(tid2)))
       {
             sleep(1);
  /*printf("oldstate:value=%d address=0x%x\n",oldstate,&oldstate);*/
  /*printf("oldtype:value=%d address=0x%x\n",oldtype,&oldtype);*/
             printf("pthread_cancel success!\n");
        }
        else
        { sleep(1);
         printf("pthread_cancel Failed!\n");
 }
 err = pthread_join(tid1, &tret);
 if (err != 0)
  

                  printf("can't join with thread 1: %s\n", strerror(err));
 printf("thread 1 exit code %d\n", (int)tret);
 err = pthread_join(tid2, &tret);
 if (err != 0)
  

                  printf("can't join with thread 2: %s\n", strerror(err));
          printf("thread 2 exit code %d\n", (int)tret);
 exit(0);
}

为了便于说明,假设

1代表pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate)

2代表pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype);

3代表pthread_testcancel();

4代表printf("oldstate:value=%d address=0x%x\n",oldstate,&oldstate);

5代表printf("oldtype:value=%d address=0x%x\n",oldtype,&oldtype);

下面说明注释掉不同的代码打印的结果

第一种 在程序注释掉这所有的5条代码

打印如下:

我们结合程序和打印结果观察 ,可知线程2在接收到主线程的取消请求后,

并不马上停下会继续运行直到到达某个取消点。线程2中可看到它已经执行了 printf("thread 2 returning\n"),取消点才到来。

第二种 使上面第三条代码有效

打印如下:

与第一种情况对比,我们在打印前设置了pthread_testcancel(),该函数的作用是在程序中自己添加取消点。所有线程2中还没打印就已经被取消了。

第三种  使上面1.4代码有效

打印如下:

与第一种情况相比, pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldstate)使pthread_cancel无效了,所有能完成退出,并且pthread_join能正确的获得的退出状态。

第四种 使上面2.5代码有效

打印如下:

与第一种情况相比,我在线程2打印前面添加了 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype),它的作用是设置线程为异步取消,通俗点就是在运行了此函数后马上取消,不受取消点的影响(此处跟第二种情况有点一样)。通过第一种

我们知道线程2的取消点是在打印了之后的某个时刻。



0 0