Ladies and gentlemen, 今天我们来说工具常考的第2个面试题:“ gdb如何调试多线程程序”的第1小节, 这个话题一共是4个小节。
【快手/腾讯面试题】gdb面试题2-1如何使用gdb调试多线程程序(后台问的最多的问题)。 秋招、校招各类面试题的讲解 https://www.bilibili.com/video/BV1Hm4y137FA/?share_source=copy_web&vd_source=1de4bbd746d463f3e044efb880331206
- 代码准备和熟悉
- 调试多线程程序的技能点
- 查看线程信息
- 切换线程
- 切换到某层调用堆栈
- 理解调度器锁模式
1. 查看和设置调度器锁
2. 测试调度器锁为step模式 - 多线程调试崩溃的例子
- 多线程调试死锁的例子
第一小节的思路:
- 模拟一个简单的多线程代码
- 编译成为可执行程序
- pstack命令 观察多线程
1. 模拟一个简单的多线程代码
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* thread_entry_funcA(void* arg){
int i = 0;
for(; i < 10; i++){
printf("[thread_entry_funcA]: %d\n", i);
sleep(1);
}
return NULL;
}
void* thread_entry_funcB(void* arg){
int i = 0;
for(; i < 10; i++){
printf("[thread_entry_funcB]: %d\n", i);
sleep(1);
}
return NULL;
}
int main(){
pthread_t tidA, tidB;
int ret = pthread_create(&tidA, NULL, thread_entry_funcA, NULL);
if(ret < 0){
perror("pthread_create");
return 0;
}
ret = pthread_create(&tidB, NULL, thread_entry_funcB, NULL);
if(ret < 0){
perror("pthread_create");
return 0;
}
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
return 0;
}
2. 编译成为可执行程序(debug版本)
[Lynn77@VM-4-12-centos thread_gdb]$ gcc thread_gdb.c -o thread_gdb -lpthread -g
[Lynn77@VM-4-12-centos thread_gdb]$ ls
thread_gdb thread_gdb.c
[Lynn77@VM-4-12-centos thread_gdb]$
3. pstack命令 观察多线程
[Lynn77@VM-4-12-centos thread_gdb]$ ps aux | grep thread
Lynn77 26477 0.0 0.0 22900 396 pts/3 Sl+ 08:48 0:00 ./thread_gdb
Lynn77 26533 0.0 0.0 112816 976 pts/4 S+ 08:48 0:00 grep --color=auto thread
[Lynn77@VM-4-12-centos thread_gdb]$ pstack 26477
Thread 3 (Thread 0x7f51a5ed4700 (LWP 26478)):
#0 0x00007f51a5f9a9fd in nanosleep () from /lib64/libc.so.6
#1 0x00007f51a5f9a894 in sleep () from /lib64/libc.so.6
#2 0x00000000004006c0 in thread_entry_funcA (arg=0x0) at thread_gdb.c:9
#3 0x00007f51a62aaea5 in start_thread () from /lib64/libpthread.so.0
#4 0x00007f51a5fd3b0d in clone () from /lib64/libc.so.6
Thread 2 (Thread 0x7f51a56d3700 (LWP 26479)):
#0 0x00007f51a5f9a9fd in nanosleep () from /lib64/libc.so.6
#1 0x00007f51a5f9a894 in sleep () from /lib64/libc.so.6
#2 0x0000000000400704 in thread_entry_funcB (arg=0x0) at thread_gdb.c:18
#3 0x00007f51a62aaea5 in start_thread () from /lib64/libpthread.so.0
#4 0x00007f51a5fd3b0d in clone () from /lib64/libc.so.6
Thread 1 (Thread 0x7f51a66d2740 (LWP 26477)):
#0 0x00007f51a62ac017 in pthread_join () from /lib64/libpthread.so.0
#1 0x0000000000400798 in main () at thread_gdb.c:38
[Lynn77@VM-4-12-centos thread_gdb]$
关注我, 给你推荐更多干货知识。
B站对应的视频