1. 在lock与unlock之间,调用pthread_exit 或者在线程外部调用pthread_cancel
其他线程被永久死锁
例子:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_tm;
void * runodd(void* d)
{
int i=0;
for(i=1;;i+=2)
{
pthread_mutex_lock(&m);
printf(“%d\n”,i);
if(i>100000)
{
pthread_exit(0);
}
pthread_mutex_unlock(&m);
}
void * runeven(void*d)
{
int i=0;
for(i=0;;i+=2)
{
pthread_mutex_lock(&m);
printf(“%d\n”,i);
pthread_mutex_unlock(&m);
}
}
void main()
{
pthread_t todd,tevent;
pthread_mutex_init(&m,0);
pthread_create(&todd,0,runodd,0);
pthread_create(&tevent,0,runeven,0);
pthread_join(tdd,(void**)0);
pthread_join(tevent,(void**)0);
pthread_mutex_destroy(&m);
}
总结:当程序打印到100001时会出现程序死锁,当线程1中线程退出时,互斥量没有减锁,m为0 进入线程2时,无法执行代码,线程1中也无法执行代码,则产生死锁。
解决方案:在线程内退出线程前先解锁。
例子2:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_tm;
void * runodd(void* d)
{
int i=0;
for(i=1;;i+=2)
{
pthread_mutex_lock(&m);
printf(“%d\n”,i);
pthread_mutex_unlock(&m);
}
void * runeven(void*d)
{
int i=0;
for(i=0;;i+=2)
{
pthread_mutex_lock(&m);
printf(“%d\n”,i);
pthread_mutex_unlock(&m);
}
}
void main()
{
pthread_t todd,tevent;
pthread_mutex_init(&m,0);
pthread_create(&todd,0,runodd,0);
pthread_create(&tevent,0,runeven,0);
sleep(5);
pthread_cancel(todd);
pthread_join(tdd,(void**)0);
pthread_join(tevent,(void**)0);
pthread_mutex_destroy(&m);
}
结论:同上程序产生死锁,但无法同上解决死锁问题。
解决方案:
pthread_cleanup_push
pthread_cleanup_pop
这对函数作用类似于atexit
注意:
这两个不是函数,而是宏。
必须成对使用
voidpthread_cleanup_pop(int execute);
voidpthread_cleanup_push(void (*routine)(void*) ,void * arg);
参数1:回调函数
参数2:传递给回调函数的指针参数
解决方案代码:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_tm;
void handle(void*d)
{
printf(“退出后的调用\n”);
pthread_mutex_unlock(&m);
}
void * runodd(void* d)
{
int i=0;
for(i=1;;i+=2)
{
pthread_mutex_lock(&m);
pthread_cleanup_push(handle,0);
sleep(1);
printf(“%d\n”,i);
pthread_cleanup_pop(0);
pthread_mutex_unlock(&m);
}
void * runeven(void*d)
{
int i=0;
for(i=0;;i+=2)
{
pthread_mutex_lock(&m);
sleep(1);
printf(“%d\n”,i);
pthread_mutex_unlock(&m);
}
}
void main()
{
pthread_t todd,tevent;
pthread_mutex_init(&m,0);
pthread_create(&todd,0,runodd,0);
pthread_create(&tevent,0,runeven,0);
sleep(5);
pthread_cancel(todd);
pthread_join(tdd,(void**)0);
pthread_join(tevent,(void**)0);
pthread_mutex_destroy(&m);
}
总结:
exit pthread_cancel函数的调用会触发pthread_cleanup_push,pthread_cleanup_pop调用。
如果pthread_cleanup_pop的参数为1也会触发该次调用,如果为0不会触发调用。