pthread_create文件读取的分段错误
pthread_create segmentation fault for file reading
我有一个类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
相同.
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?