【问题标题】:pthread program results in segmentation faultpthread 程序导致分段错误
【发布时间】: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;
}

这可能是一个愚蠢的原因导致它无法正常工作,所以我希望你们找到它不会太麻烦!

【问题讨论】:

标签: c pthreads


【解决方案1】:
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 即可解决此问题。

【讨论】:

    【解决方案2】:

    您的启动例程名称和线程 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;
    }
    

    【讨论】:

    • 实际上,编译器并没有感到困惑,它完全按照它的指示去做。混乱发生在开发过程的早期:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2013-04-11
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多