方法1:通过core文件调试死锁
步骤:
1. ulimited -c unlimted(打开core,默认没有打开)
2. 运行./a.out(编译的时候加调试选项-g) 死锁阻塞,Ctrl+\ 产生core dump
3. gdb ./a.out core.xxx
4. thread apply all bt查看死锁位置
例子(待续…)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
int i = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* start_routine(void *arg)
{
int j;
char *str = (char*)arg;
for (j=0; j<100; ++j)
{
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex); //死锁产生的位置
printf("i=%d, from %s\n",i, arg);
//pthread_mutex_lock(&mutex);
i++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void)
{
pthread_t pid1,pid2;
char *str1 = "A";
char *str2 = "B";
pthread_create(&pid1,NULL,start_routine,(void*)str1);
pthread_join(pid1,NULL);
return 0;
}
执行第4步,thread apply all bt,如下图
可以看见造成死锁的位置。
方法2: gdb attach pid
步骤
1. 运行./a.out(编译的时候加调试选项-g)
2. ps -ef | grep a.out找到其线程pid(比如是12345)
3. gdb a.out 12345 进入gdb
4. info threads 查看线程
5. thread 1(2) 等等进入某个thread
6. bt(打印某个线程的堆栈)
当然也可以在第3步后直接进行thread apply all bt