pthread_create文件读取的分段错误

pthread_create segmentation fault for file reading

本文关键字:分段 错误 读取 文件 create pthread      更新时间:2023-10-16

我有一个类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 函数是按顺序运行的,如果在下一个线程完成之前创建新线程会不会有问题?

问题是您将指向局部变量 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相同.