【问题标题】:Simple pthread prog: segmentation fault简单的 pthread prog:分段错误
【发布时间】:2022-01-07 18:19:42
【问题描述】:

试图通过运行一个简单的程序来查看 pthread 的工作原理,但我在 pthread_create 处遇到分段错误(核心转储)

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

void* testfunc(void* arg) {
  while (1) {
    printf("testfunc");
  }
}

int main(void) {
  printf("helo\n");

  if (pthread_create(NULL, NULL, &testfunc, NULL) != 0) {
    perror("pthread failed to create\n");
  }

  while (1) {
    printf("main function\n");
    sleep(1000);
  } 

  return 0;
}

似乎是什么导致了问题?如果这很重要,我在 Ubuntu 20.04 上。

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    您不能将NULL 传递给pthread_create 的第一个参数。

    在返回之前,对pthread_create()的成功调用会将新线程的ID存储在thread指向的缓冲区中

    另外,pthread_create 没有设置 errno,所以使用 perror 没有任何意义,至少在没有一些准备的情况下是这样。

    出错时返回错误号,*thread 的内容未定义。

    固定:

    pthread_t thread;
    if ( ( errno = pthread_create(&thread, NULL, &testfunc, NULL) ) != 0 ) {
        perror("pthread failed to create\n");
    }
    
    ...
    
    pthread_join(thread, ...);  // Normally.
    

    【讨论】:

    • 我看到了一些文档mkssoftware.com/docs/man3/pthread_create.3.asp,它基本上说第一个 arg 可以为 NULL,具体取决于用例。那么你是否允许传递 NULL 或根本不传递?怎么回事?
    • @Iberico 很明显,您的系统不允许它为 NULL,这与当前的 Linux 文档相匹配。您可以查看 POSIX 规范以了解它需要什么以及它允许​​什么
    【解决方案2】:

    c 中的线程非常无情。我可以看到您的代码存在一些问题。

    首先,您可能需要参考 p_thread 的开发者文档。他们有很好的记录。您当前拥有的是一个线程调用,但您没有指向该线程的任何内容。这就是您收到分段错误的原因。这意味着您的程序在尝试调用它时丢失了指向该线程的指针。我建议类似的东西。

    pthread_t thread;
    int * argument = 5;
    if(pthread_create(&thread,NULL, &testfunc, &argument) !=0){
    //                                        ^This is a pointer to your argument 
    //                                         that you want to pass in
       perror("pthread failed to create\n");
       exit(1);
    }
    

    并且您的线程函数还需要从 void 指针类型转换为您希望它返回工作的任何内容。然后需要在从线程例程返回之前将其转换回一个 void 指针。

    void* testfunc(void* arg){
      int* testVar = (int *)arg;
    
      // do some logic here
    
      return (void *) testVar;
    }
    

    最后,你要对 C 中的内存负责,所以你必须在退出之前杀死你创建的线程。

    pthread_join(thread, NULL);
    

    我的第一个建议是你观看一些与之相关的视频。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2011-10-26
      • 2016-11-05
      • 2015-01-08
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      相关资源
      最近更新 更多