【发布时间】:2019-09-16 16:08:03
【问题描述】:
最近我一直在学习 pthread。然后我突然冒出一个想法,gdb怎么知道我创建了一个新线程。然后我在下面写了一个测试代码并启动了gdb。我进入 pthread_create() 函数,但不是让它正常返回,而是使用return 0 返回 pthread_create() 函数。但是 gdb 仍然显示我只有一个线程。起初,我认为 gdb 从 pthread_create() 函数的返回值中获取线程信息,然后我认为 gdb 也可能使用子进程信息来获取线程信息,所以我编辑了我的测试代码。但结果不是我想的那样。
那么 gdb 是如何获取线程信息的呢?它需要什么样的信息才能知道主线程有多少个线程以及我在哪个线程上。
代码
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include "pthread.h"
void *foo(void *bar) {
while(1) {
printf("hello from thread: %d\n", pthread_self());
sleep(2);
}
}
int main() {
printf("Before fake pthread_create");
pid_t pid;
if ((pid = fork()) == -1) {
perror("fork error");
exit(errno);
}
if (pid == 0) {
while(1) {
sleep(3);
}
}
if (pid > 0) {
pthread_t thread;
pthread_create(&thread, NULL, foo, NULL);
while(1) {
printf("hello from thread: %d\n", pthread_self());
sleep(2);
}
return 0;
}
}
【问题讨论】:
-
出于所有实际目的,在线程函数的第一行设置一个断点