【发布时间】:2021-10-02 19:32:03
【问题描述】:
我一直在尝试用 C 语言创建一个带有线程的聊天程序,但它没有工作,所以我决定先玩一下线程。我正在尝试运行一个打印“hello world”的线程,但它给了我一个分段错误。我一直无法找到问题的根源,所以我来到了这里。代码如下:
#include <stdio.h>
#include <pthread.h>
void* test(void * arg) {
printf("hello world\n");
return NULL;
}
int main() {
pthread_t test;
pthread_create(&test, NULL, (void *) test, NULL);
pthread_exit(NULL);
return 0;
}
这可能是一个愚蠢的原因导致它无法正常工作,所以我希望你们找到它不会太麻烦!
【问题讨论】:
-
pthread_create 的第三个参数是指局部变量,而不是你想的函数。
-
你需要一个
pthread_join请参阅:stackoverflow.com/questions/68534498/c-posix-thread-basics 对非常相似的代码进行一些修复