首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

Linux多线程程序中某个线程在添互斥锁后挂掉,系统会死锁吗

2013-03-14 
Linux多线程程序中某个线程在加互斥锁后挂掉,系统会死锁吗?问题是这个样子的:多个线程用pthread_mutex_t l

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
terminate called after throwing an instance of 'std::bad_alloc'


  what():  std::bad_alloc
已放弃 (核心已转储)

线程中抛异常是会终止整个进程的。。
我觉得楼主不用为这种事而操心。
因为据我有限的了解,你说的这种情况,连POSIX标准中都没有对止的解决方案。对我上帖出现的情况就有pthread_cleanup_push/pop的解决方案。
所以你就当他不可能发生就行了。 
[解决办法]
线程挂了进程还能活吗..

热点排行