【问题标题】:pthread_join causes segmentation error (simple program)pthread_join 导致分段错误(简单程序)
【发布时间】:2013-04-11 14:51:20
【问题描述】:

我只是在尝试使用多线程程序,但我遇到了 pthread_join 函数的问题。下面的代码只是我用来显示 pthread_join 崩溃的一个简单程序。此代码的输出将是:

before create

child thread

after create

Segmentation fault (core dumped)

是什么导致 pthread_join 给出分段错误?

#include <pthread.h>
#include <stdio.h>

void * dostuff() {
    printf("child thread\n");
    return NULL;
}

int main() {
    pthread_t p1;

    printf("before create\n");
    pthread_create(&p1, NULL, dostuff(), NULL);
    printf("after create\n");

    pthread_join(p1, NULL);
    printf("joined\n");

    return 0;
}

【问题讨论】:

  • 您确定已启用并听取了所有编译器警告吗?这看起来有很多可以避免的错误。

标签: c multithreading segmentation-fault pthreads pthread-join


【解决方案1】:

你需要修正你的函数类型和你调用pthread_create的方式:

void * dostuff(void *) { /* ... */ }
//             ^^^^^^

pthread_create(&p1, NULL, dostuff, NULL);
//                        ^^^^^^^

【讨论】:

    【解决方案2】:

    因为在您调用pthread_create 时,您实际上调用 函数,并且当它返回NULL pthread_create 时会失败。这将无法正确初始化 p1,因此(可能)会导致 pthread_join 调用中出现未定义的行为。

    要解决此问题,请将函数指针传递给 pthread_create 调用,不要调用它:

    pthread_create(&p1, NULL, dostuff, NULL);
    /* No parantehsis --------^^^^^^^ */
    

    这也应该教你检查函数调用的返回值,因为pthread_create 将在失败时返回非零值。

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2015-05-02
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多