pthread 程序导致分段错误

pthread program results in segmentation fault

我一直在尝试用 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;
}

它不起作用可能有一个愚蠢的原因,所以我希望你们找到它不会太麻烦!

void* test(void * arg) { ... }

//        vvvv
pthread_t test;
pthread_create(&test, NULL, (void *) test, NULL);
//                                   ^^^^

pthread_t 变量“隐藏”了函数名称。换句话说,您正在调用一些任意的未初始化值作为您的函数。这不太可能有好结果:-)

您所做的与期望以下程序输出 7(不会)真的没有什么不同:

#include <stdio.h>
int i = 7;
int main(void) {
    int i = 42;
    printf("%d\n", i);
    return 0;
}

例如,您只需将函数重命名为 testFn 即可解决此问题。

您的启动例程名称和线程 ID 名称相同,因此我认为当您通过 &test 时编译器会感到困惑。您的代码通过更改线程 ID 名称来工作。

#include <stdio.h>

#include <pthread.h>

void* test(void * arg) {
    printf("hello world\n");
    return NULL;
}

int main() {
    pthread_t t;
    pthread_create(&t, NULL, (void *) test, NULL);
    pthread_exit(NULL);

    return 0;
}