在线程运行中,很有可能被其他线程使用pthread_cancel()函数取消掉,如果取消线程后还有互斥锁没有解锁,那么就会造成死锁状态。使用pthread_cleanup_push(handler, NULL)函数和pthread_cleanup_pop()函数可以避免死锁情况发生
1、相关API函数原型
注意:
1、如果线程退出时没有返回值,则设置为NULL
2、pthread_join()指定的进程如果还在运行,则将阻塞等待
3、pthread_tryjoin_np()指定的线程还在运行,则立即返回出错返回
2.例子:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
pthread_mutex_t m;
void handler(void *arg)
{
pthread_mutex_unlock(&m);
}
void *Routine(void *arg)
{
// pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); //取消线程功能disable,pthread_cancel()无效
pthread_cleanup_push(handler, NULL); //加锁前,将handler函数压入贤臣取消处理例程的栈中,以防中途线程被取消,当线程被取消是执行handler函数
pthread_mutex_lock(&m);
printf("tid1 printf\n");
sleep(5); //延迟5秒为了等待main线程取消线程tid1
pthread_mutex_unlock(&m);
pthread_cleanup_pop(0); //将handler函数从栈中弹出,但不执行handler函数
pthread_exit("routine exit"); //正常退出,并返回"routine exit"
}
int main(int argc, void *argv[])
{
pthread_mutex_init(&m, NULL);
pthread_t tid1;
pthread_create(&tid1, NULL, Routine, NULL);
sleep(1);
pthread_cancel(tid1); //取消线程tid1
pthread_mutex_lock(&m);
printf("main printf\n");
pthread_mutex_unlock(&m);
// void *p;
// pthread_join(tid1, &p); //阻塞等待子线程tid1退出,并获取子线程返回值
// printf("tid1 exit receive:%s\n", (char *)p );
pause();
exit(0);
}