日期:2014-05-16  浏览次数:20713 次

Linux多线程程序中某个线程在加互斥锁后挂掉,系统会死锁吗?
问题是这个样子的:
多个线程用pthread_mutex_t lock互斥锁并发访问共享数据结构。

其中某个线程在执行完
pthread_mutex_lock(&lock);之后由于某种原因挂了,
使得pthread_mutex_unlock(&lock);未执行。

那么整个系统会产生死锁吗?
谢谢!
互斥锁 死锁 core掉 多线程

------解决方案--------------------
一般不会出现单个线程挂掉的情况吧,除非程序逻辑上有问题,被线程被别的线程cancel或者自己在不该退出的地方用了pthread_exit了,要挂也是整个进程挂了。
如果真出现这种情况,肯定会死锁了。
楼主可以看看pthread_cleanup_push()/pthread_cleanup_pop()这两个函数,,就是处理LOCK和UNLOCK之间被cancel的情形的。
man pthread_cleanup_push中的一段话:
for example, unlock a mutex
       so that it becomes available to other threads in the process.
...
       A cancellation clean-up handler is popped from the stack  and  executed
       in the following circumstances:

       1. When  a thread is canceled, all of the stacked clean-up handlers are
          popped and executed in the reverse of the order in which  they  were
          pushed onto the stack.

       2. When  a  thread  terminates by calling pthread_exit(3), all clean-up
          handlers are executed as described in the preceding point.   (Clean-
          up  handlers are not called if the thread terminates by performing a
          return from the thread start function.)

       3. When a thread calls pthread_cleanup_pop()  with  a  nonzero  execute
          argument, the top-most clean-up handler is popped and executed.
------解决方案--------------------
引用:
引用:一般不会出现单个线程挂掉的情况吧,除非程序逻辑上有问题,被线程被别的线程cancel或者自己在不该退出的地方用了pthread_exit了,要挂也是整个进程挂了。
如果真出现这种情况,肯定会死锁了。
楼主可以看看pthread_cleanup_push()/pthread_cleanup_pop()这两个函数,,就是处理LOCK……

实验下:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <new>

using std::bad_alloc;

void *thread(void *arg)
{
printf("in thread\n");
throw bad_alloc();

while(true) {
sleep(1);
printf("thread after\n");
}
return NULL;
}

int main(void)
{
pthread_t tid;
void *ret;
pthread_create(&tid, NULL, thread, NULL);
pthread_join(tid, NULL);
printf("after join\n");
return 0;
}

结果:
in thread