1.假設(shè)有兩個(gè)線(xiàn)程
A線(xiàn)程負(fù)責(zé)輸出奇數(shù)。B線(xiàn)程負(fù)責(zé)輸出偶數(shù)
2.當(dāng)A線(xiàn)程進(jìn)入鎖定狀態(tài)時(shí)候,主線(xiàn)程突然異常將A線(xiàn)程停止舅柜,這時(shí)將導(dǎo)致B線(xiàn)程也無(wú)法繼續(xù)執(zhí)行迟隅,處于死鎖狀態(tài)但骨。如下代碼:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
static pthread_mutex_t mutex;
void* run01(void *argv)
{
int i = 1;
for(i;;i=i+2)
{
pthread_mutex_lock(&mutex);
printf("奇數(shù)...[%d]\n",i);
sleep(5);
pthread_mutex_unlock(&mutex);
}
}
void* run02(void *argv)
{
int i=2;
for(i;;i=i+2)
{
pthread_mutex_lock(&mutex);
printf("偶數(shù)...[%d]\n",i);
sleep(6);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc,char *argv[])
{
pthread_t thread[2];
pthread_mutex_init(&mutex,0);
for(int i=0;i<2;++i)
{
if(0==i)
{
pthread_create(&thread[i],NULL,run01,NULL);
}
else
{
pthread_create(&thread[i],NULL,run02,NULL);
}
}
sleep(5);
printf("外部強(qiáng)勢(shì)結(jié)束thread[0]線(xiàn)程...\n");
pthread_cancel(thread[0]);
pthread_join(thread[0],(void **)0);
pthread_join(thread[1],(void **)0);
pthread_mutex_destroy(&mutex);
return 0;
}
解決方法:
運(yùn)用2個(gè)函數(shù)(其實(shí)是2個(gè)宏)
pthread_cleanup_push
pthread_cleanup_pop 這個(gè)對(duì)函數(shù)作用類(lèi)似于atexit函數(shù)
注意:這不是函數(shù)而是宏励七。必須成對(duì)使用。
void pthread_cleanup_push(
void (*routine)(void *),//回調(diào)函數(shù)
void *arg //回調(diào)函數(shù)的參數(shù)
);
觸發(fā)調(diào)用routine的條件:
1.執(zhí)行了exit()奔缠。
2.執(zhí)行了pthread_cancel()
3.pthread_cleanup_pop(1);//參數(shù)必須是1
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t m;
void handle(void *d)
{
printf("退出后的調(diào)用呀伙!\n");
pthread_mutex_unlock(&m);
}
void *runodd(void *d)
{
int i=0;
for(i=1;;i+=2)
{
pthread_cleanup_push(handle,0);
pthread_mutex_lock(&m);
printf("奇數(shù):%d\n",i);
usleep(100);
pthread_mutex_unlock(&m);
pthread_cleanup_pop(0);
}
}
void *runeven(void *d)
{
int i=0;
for(i=0;;i+=2)
{
pthread_mutex_lock(&m);
printf("偶數(shù):%d\n",i);
usleep(100);
pthread_mutex_unlock(&m);
}
}