pthread_create文件读取的分段错误

时间:2016-04-27 10:07:51

标签: c++ multithreading class pthreads

我有一个类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函数已在static内声明为Class1,其结构如下:

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

所有这些都会导致分段错误。我怎么解决? 此外,由于Run函数按顺序运行,如果在下一个线程完成之前创建新线程,是否会出现问题?

1 个答案:

答案 0 :(得分:3)

问题是你传递一个指向局部变量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相同。

相关问题