取消线程:
功能:取消一个正在执行线程的操作。一个线程能够被取消需要满足条件
条件:一:该线程是否可以被其他取消是可设置的,
PTHREAD_CANCEL_DISABLE PTHREAD_CANCEL_ENABLE
二:该线程处于可取消点才能取消typedef unsigned long pthread_t // %lu
需要在 可取消状态 PTHREAD_CANCEL_ENABLE 是,才能被取消
extern int pthread_cancel (pthread_t __cancelthread)
设置可取消状态
查询当前线程的可取消性状态
extern int pthread_setcancelstate(int __state, int *__oldstate);
设置取消类型
extern int pthread_setcanceltype(int __type,int *__oldstate)
type = PTHREAD_CANCEL_ENABLE
type = PTHREAD_CANCEL_DISABLE函数描述:
主线程使用 pthread_cancle 取消线程。但是在子线程中用 pthread_setcancelstate 设置了 PTHREAD_CANCEL_DISABLE, 所以不能被取消,主线程处于等待状态。经过一段时间,子线程 设置为
PTHREAD_CANCEL_ENABLE ,现在就可以取消子线程操作了,主线程就取消了子线程的运行代码: pthread_cancel.rar gcc main.c -lpthread -o main- #include <stdio.h>
-
#include <stdlib.h>
-
#include <pthread.h>
-
-
void *thread_fun(void *a);
-
-
int main(int argc, char *argv[])
-
{
-
int res;
-
pthread_t a_thread;//typedef unsigned long pthread_t &lu
-
void *thread_result;
-
-
res = pthread_create(&a_thread, NULL, (void *)*thread_fun, NULL); //建立子线程
-
if(res != 0)
-
{
-
perror("thread create failed");
-
exit(1);
-
}
-
-
sleep(10);
-
-
printf("cancle thread...\n");
-
res = pthread_cancel(a_thread); //取消子线程
-
if(res != 0)
-
{
-
perror("thread cancle failed");
-
exit(1);
-
}
-
-
printf("waiting for thread to finish...\n");
-
res = pthread_join(a_thread, &thread_result); //退出 子线程
-
if(res != 0)
-
{
-
perror("thread join failed");
-
exit(1);
-
}
-
-
exit(EXIT_SUCCESS);
-
}
-
-
void *thread_fun(void *a)
-
{
-
int i,res,j; //存放在 栈中 临时变量
-
sleep(1);
-
-
res = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); //设置取消状态 DISABLE
-
if(res != 0)
-
{
-
perror("pthread setcanclestate failed");
-
exit(EXIT_FAILURE);
-
}
-
-
sleep(3);
-
-
printf("thread cancel type is disable ,can't cancle this thread\n"); //打印不可取状态信息
-
for(i = 0; i < 3; i++)
-
{
-
printf("thread is running(%d)...\n",i);
-
sleep(1);
-
}
-
-
res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
-
if(res != 0)
-
{
-
perror("pthread_setcanclestat failed");
-
exit(EXIT_FAILURE);
-
}
-
else
-
{
-
printf("now change the canclestate is ENABLE\n");
-
}
-
sleep(200);
-
-
pthread_exit(NULL); //没有返回到 主线程信息
-
-
}
- ywx@yuweixian:~/yu/professional/4$ ./pthread_cancel
-
thread cancel type is disable ,can't cancle this thread
-
thread is running(0)...
-
thread is running(1)...
-
thread is running(2)...
-
now change the canclestate is ENABLE
-
cancle thread...
-
waiting for thread to finish...
阅读(1674) | 评论(0) | 转发(1) |