是否有可能以确定该线程持有互斥锁? [英] Is it possible to determine the thread holding a mutex?

查看:229
本文介绍了是否有可能以确定该线程持有互斥锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我用pthread库编写多线程C程序。主题总是以等待mutexs挂起。当我使用strace的工具来找到一个线程在FUTEX_WAIT状态,我想知道哪个线程当时认为互斥。但我不知道我怎么能做到这一点。是否有任何事业能做到这一点?
有人告诉我的Java虚拟机支持这一点,所以我想知道是否Linux支持此功能。

Firstly, I use pthread library to write multithreading c program. Threads always hung by their waited mutexs. When I use the strace utility to find a thread is in FUTEX_WAIT status, I want to know which thread hold that mutex at the time. But I don't know how could I make it. Are there any utilities could do that? Someone told me java virtual machine support this, So I want to know whether linux support this feature.

推荐答案

您可以使用互斥体内部的知识来做到这一点。按说这不会是一个很不错的主意,但它是很好调试。

You can use knowledge of the mutex internals to do this. Ordinarily this wouldn't be a very good idea, but it's fine for debugging.

在Linux下的NPTL实现pthreads的(这是任何现代的glibc),您可以检查 pthread_mutex_t <的 __数据.__所有者成员/ code>结构,找出目前它锁定的线程。这是如何连接到进程后,做 GDB

Under Linux with the NPTL implementation of pthreads (which is any modern glibc), you can examine the __data.__owner member of the pthread_mutex_t structure to find out the thread that currently has it locked. This is how to do it after attaching to the process with gdb:

(gdb) thread 2
[Switching to thread 2 (Thread 0xb6d94b90 (LWP 22026))]#0  0xb771f424 in __kernel_vsyscall ()
(gdb) bt
#0  0xb771f424 in __kernel_vsyscall ()
#1  0xb76fec99 in __lll_lock_wait () from /lib/i686/cmov/libpthread.so.0
#2  0xb76fa0c4 in _L_lock_89 () from /lib/i686/cmov/libpthread.so.0
#3  0xb76f99f2 in pthread_mutex_lock () from /lib/i686/cmov/libpthread.so.0
#4  0x080484a6 in thread (x=0x0) at mutex_owner.c:8
#5  0xb76f84c0 in start_thread () from /lib/i686/cmov/libpthread.so.0
#6  0xb767784e in clone () from /lib/i686/cmov/libc.so.6
(gdb) up 4
#4  0x080484a6 in thread (x=0x0) at mutex_owner.c:8
8               pthread_mutex_lock(&mutex);
(gdb) print mutex.__data.__owner
$1 = 22025
(gdb)

(我切换到挂起线程;做一个回溯,找到 pthread_mutex_lock()的它停留在;改变堆栈帧,找出它的互斥体的名称试图锁定;然后打印该互斥体的所有者)。这告诉我,与线程ID 22025线程是罪魁祸首。

(I switch to the hung thread; do a backtrace to find the pthread_mutex_lock() it's stuck on; change stack frames to find out the name of the mutex that it's trying to lock; then print the owner of that mutex). This tells me that the thread with thread id 22025 is the culprit.

这篇关于是否有可能以确定该线程持有互斥锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆