当前位置: 技术问答>linux和unix
Linux多线程程序中某个线程在加互斥锁后挂掉,系统会死锁吗?
来源: 互联网 发布时间:2017-04-02
本文导语: 问题是这个样子的: 多个线程用pthread_mutex_t lock互斥锁并发访问共享数据结构。 其中某个线程在执行完 pthread_mutex_lock(&lock);之后由于某种原因挂了, 使得pthread_mutex_unlock(&lock);未执行。 那么整个系统会产生死锁吗...
问题是这个样子的:
多个线程用pthread_mutex_t lock互斥锁并发访问共享数据结构。
其中某个线程在执行完
pthread_mutex_lock(&lock);之后由于某种原因挂了,
使得pthread_mutex_unlock(&lock);未执行。
那么整个系统会产生死锁吗?
谢谢!
多个线程用pthread_mutex_t lock互斥锁并发访问共享数据结构。
其中某个线程在执行完
pthread_mutex_lock(&lock);之后由于某种原因挂了,
使得pthread_mutex_unlock(&lock);未执行。
那么整个系统会产生死锁吗?
谢谢!
|
实验下:
#include
#include
#include
#include
using std::bad_alloc;
void *thread(void *arg)
{
printf("in threadn");
throw bad_alloc();
while(true) {
sleep(1);
printf("thread aftern");
}
return NULL;
}
int main(void)
{
pthread_t tid;
void *ret;
pthread_create(&tid, NULL, thread, NULL);
pthread_join(tid, NULL);
printf("after joinn");
return 0;
}
结果:
in thread
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
已放弃 (核心已转储)
线程中抛异常是会终止整个进程的。。
我觉得楼主不用为这种事而操心。
因为据我有限的了解,你说的这种情况,连POSIX标准中都没有对止的解决方案。对我上帖出现的情况就有pthread_cleanup_push/pop的解决方案。
所以你就当他不可能发生就行了。
|
一般不会出现单个线程挂掉的情况吧,除非程序逻辑上有问题,被线程被别的线程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.
如果真出现这种情况,肯定会死锁了。
楼主可以看看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.
|
线程挂了进程还能活吗..