1. 程式人生 > >使用gdb除錯死鎖執行緒

使用gdb除錯死鎖執行緒

1.除錯檔案 lock.c

 

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *work_thread(void *arg)
{
	pthread_mutex_t mutex;
	pthread_mutex_init(&mutex, 0);
	usleep(1000*1000);
	fprintf(stderr, "timeout we will start dead lock\n");
	pthread_mutex_lock(&mutex);
	pthread_mutex_lock(&mutex);
}

void *alive_thread(void *arg)
{
	while (1)
	{
		usleep(1000*1000);
	}
}

int main()
{
	pthread_t alive_pid;
	pthread_create(&alive_pid, 0, alive_thread, 0);
	pthread_t dead_pid;
	pthread_create(&dead_pid, 0, work_thread, 0);
	void *ret = NULL;
	pthread_join(dead_pid, &ret);
	void *ret2 = NULL;
	pthread_join(alive_pid, &ret2);
	return 0;
}

 

2.編譯執行 lock.c
[[email protected] ~]# gcc -g lock.c -pthread
[[email protected] ~]# ./a.out
timeout we will start dead lock

(程式掛起)

 

3.查詢程序id

[[email protected] ~]# ps -e | grep a.out

12826 pts/3    00:00:00 a.out //程序id為12826

 

4.啟動gdb attach 程序

[[email protected]

~]# gdb a.out 12826
GNU gdb (GDB) CentOS (7.0.1-45.el5.centos)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /root/a.out...done.
Attaching to program: /root/a.out, process 12826
Reading symbols from /lib/libpthread.so.0...(no debugging symbols found)...done.
[Thread debugging using libthread_db enabled]
[New Thread 0xb7524b90 (LWP 12828)]
[New Thread 0xb7f25b90 (LWP 12827)]
Loaded symbols for /lib/libpthread.so.0
Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/ld-linux.so.2
0x00502402 in __kernel_vsyscall ()
(gdb) info threads //顯示所有執行緒資訊

  3 Thread 0xb7f25b90 (LWP 12827)  0x00502402 in __kernel_vsyscall ()
  2 Thread 0xb7524b90 (LWP 12828)  0x00502402 in __kernel_vsyscall ()
* 1 Thread 0xb7f266c0 (LWP 12826)  0x00502402 in __kernel_vsyscall ()
(gdb) thread 2  //跳到第2個執行緒
[Switching to thread 2 (Thread 0xb7524b90 (LWP 12828))]#0  0x00502402 in __kernel_vsyscall ()
(gdb) bt  //檢視執行緒2的堆疊,可以發現該執行緒堵塞在lock.c第17行
#0  0x00502402 in __kernel_vsyscall ()
#1  0x0072e839 in __lll_lock_wait () from /lib/libpthread.so.0
#2  0x00729e9f in _L_lock_885 () from /lib/libpthread.so.0
#3  0x00729d66 in pthread_mutex_lock () from /lib/libpthread.so.0
#4  0x080485b4 in work_thread (arg=0x0) at lock.c:17
#5  0x00727912 in start_thread () from /lib/libpthread.so.0
#6  0x0066660e in clone () from /lib/libc.so.6
(gdb) 


參考自 http://blog.csdn.net/openxmpp/article/details/8615000