【问题标题】:pthread_create segmentation fault for file reading文件读取的 pthread_create 分段错误
【发布时间】:2016-04-27 10:07:50
【问题描述】:

我有一个类Class1 有一个方法Class1::Run 被顺序调用。在这个方法中,我想加载一些文本文件,有时是大文件,并执行一些操作。由于此文本文件需要一些时间来加载,我想将它们加载到不同的线程中,并在等待它们准备好时执行一些替代操作。在这个线程中,我想调用另一个类的方法来加载文件。

我创建了以下结构:

struct args {
   int cmd;
   Class2 * object2;
}

这是Class1::Run的结构:

pthread load_thread;
struct args thread_args;
thread_args.cmd = 0; //this is used to specify the kind of file to be loaded
thread_args.object2 = object2;
pthread_create( &load_thread, NULL, &ThreadHelper, (void*) &thread_args );

object2 已在 Class1 中声明为 Class2 * object2 并在其他地方初始化。

ThreadHelper 函数已在 Class1 内部声明为 static,其结构如下:

void * Class1::ThreadHelper(void * thread_args) {
   struct args * targs = (struct args*) thread_args;
   targs->object2->LoadFile(targs->cmd);
}

所有这些都导致了分段错误。我该如何解决? 另外,由于 Run 函数是按顺序运行的,如果在下一个线程完成之前创建一个新线程会不会有问题?

【问题讨论】:

    标签: c++ multithreading class pthreads


    【解决方案1】:

    问题是你向线程传递了一个指向局部变量thread_args 的指针。您应该将其设为全局变量 - 将其移至函数外部,或在堆上分配,即:

    pthread load_thread;
    struct args* thread_args=new args;
    thread_args->cmd = 0; //this is used to specify the kind of file to be loaded
    thread_args->object2 = object2;
    pthread_create( &load_thread, NULL, &ThreadHelper, (void*) thread_args );
    

    完成工作后不要忘记在线程函数中删除它(您可以使用 std::unique_ptr 使其自动执行)。


    现在我看到您可以将 struct args thread_args; 移动到 Class1 - 与 object2 相同。

    【讨论】:

    • 我已经尝试了第二件事,但它仍然给我同样的结果。我现在尝试第一个解决方案
    • @charles 至于第二个建议:确保在你的线程完成之前,拥有thread_args 的Class1 实例不会被销毁。
    猜你喜欢
    • 2011-07-28
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2012-01-05
    • 1970-01-01
    相关资源
    最近更新 更多