二、线程的取消。
1、通过发送一个取消请求给线程,那么这个线程就会退出。 --> pthread_cancel() --> man 3 pthread_cancel
功能: send a cancellation request to a thread
//给一个线程发送取消请求
使用格式:
#include <pthread.h>
int pthread_cancel(pthread_t thread);
参数:
thread: 线程的ID号
返回值:
成功:0
失败:非0
----------------------------------------
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *func(void *arg)
{
int i;
for(i=0;i<10;i++)
{
printf("i = %d\n",i);
sleep(1);
}
}
int main(int argc,char *argv[])
{
pthread_t tid;
pthread_create(&tid,NULL,func,NULL);
sleep(3);
pthread_cancel(tid);
sleep(2);
printf("main thread exit!\n");
return 0;
}
-----------------------------------------
2、设置线程响应取消的状态。 --> pthread_setcancelstate() --> man 3 pthread_setcancelstate
功能: set cancelability state
//设置线程取消状态
#include <pthread.h>
int pthread_setcancelstate(int state, int *oldstate);
参数:
state:设置的状态
PTHREAD_CANCEL_ENABLE --> 能响应取消请求(默认属性)
PTHREAD_CANCEL_DISABLE --> 不能响应取消请求
oldstate: 保留之前状态的指针,如果不关心,则设置为NULL
返回值:
成功:0
失败:非0
练习3: 验证以下的结论是对的。
If a cancellation request is received, it is blocked until cancelability is enabled.
//如果在不能响应取消请求的过程中,收到了取消请求,那么这个取消请求就会一直阻塞到能响应取消为止。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *func(void *arg)
{
//默认就是能响应取消请求
//1. 将线程设置为不能响应取消
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
//2. 现在,就是不能响应取消的
int i;
for(i=0;i<10;i++)
{
printf("disable!\n");
sleep(1);
}
//3. 10s,将线程设置为能响应取消
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
//4. 让能响应取消状态持续10s
for(i=0;i<10;i++)
{
printf("enable!\n");
sleep(1);
}
}
int main(int argc,char *argv[])
{
//1. 创建一个普通线程
pthread_t tid;
pthread_create(&tid,NULL,func,NULL);
//2. 3s后,给线程发送一个取消请求
pthread_cancel(tid);
printf("I send cancel to child thread!\n");
//3. 接合
pthread_join(tid,NULL);
return 0;
}
3、设置线程取消的类型。 ---> pthread_setcanceltype() --> man 3 pthread_setcanceltype
#include <pthread.h>
int pthread_setcanceltype(int type, int *oldtype);
参数:
type: 设置的类型
PTHREAD_CANCEL_DEFERRED- --> 延迟响应(收到取消请求时,不会马上响应,而是等到线程遇到取消点函数为止)
PTHREAD_CANCEL_ASYNCHRONOUS --> 马上响应
oldtype: 保留之前类型旧的指针,如果不关心,则设置为NULL
延迟取消模型:
xxxx; <--- 收到了取消请求
xxxx;
xxxx;
xxxx;
xxxx;
xxxx; -> 取消点函数
什么是取消点函数? --> man 7 pthreads
fputc()
fputs()
sleep()
usleep()
printf()
例题2: 验证延迟取消的情况。
xxxxx; <--- 取消请求
xxxxx;
xxxxx;
fputc()
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *func(void *arg)
{
//默认是延迟取消
int i,j;
for(i=0;i<100000;i++)
{
for(j=0;j<100000;j++)
{
//都不是取消点函数
}
}
while(1)
{
fputc('x',stderr); //取消点函数
printf("helloworld!\n"); //取消点函数
}
}
int main(int argc,char *argv[])
{
pthread_t tid;
pthread_create(&tid,NULL,func,NULL);
pthread_cancel(tid);
printf("I send cancel to child!\n");
pthread_join(tid,NULL);
return 0;
}