简体   繁体   English

pthread_create用于读取文件的分段错误

[英]pthread_create segmentation fault for file reading

I have a class Class1 with a method Class1::Run that is called sequentially. 我有一个带有方法Class1::Run的类Class1 ,该方法被顺序调用。 Inside this method I want to load some text files, sometimes big ones, and perform some operations. 在此方法内部,我想加载一些文本文件,有时是大文件,并执行一些操作。 Since this text files take some time to load, I would like to load them in a different thread and perform some alternative operations while waiting for them to be ready. 由于加载这些文本文件需要一些时间,因此我想将它们加载到其他线程中,并在等待它们准备就绪时执行一些替代操作。 In this thread I would like to call another class' method to load the files. 在这个线程中,我想调用另一个类的方法来加载文件。

I have created the following struct: 我创建了以下结构:

struct args {
   int cmd;
   Class2 * object2;
}

This is the structure of Class1::Run : 这是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 has been declared in Class1 as Class2 * object2 and initialized somewhere else. object2Class1中已声明为Class2 * object2并已在其他地方初始化。

The ThreadHelper function has been declared as static inside Class1 and it is structured as follows: ThreadHelper函数在Class1内部已声明为static ,其结构如下:

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

All this is causing a segmentation fault. 所有这些都导致分段错误。 How can I solve? 我该如何解决? Also, since the Run function runs sequentially, could it be a problem if a new thread is created before the next one has finished? 另外,由于Run函数是按顺序运行的,因此如果在下一个线程完成之前创建了一个新线程,可能会出现问题吗?

The problem is that you pass to thread a pointer to local variable thread_args . 问题是您将指向本地变量thread_args的指针传递给线程。 You should make it either global variable - move it outside function, or allocate it on heap, ie: 您应该使它成为全局变量-将其移到函数外部,或将其分配到堆上,即:

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 );

and dont forget to delete it inside thread function after you are done with its work (you may use std::unique_ptr to make it automatic). 并且不要忘记在完成线程工作后将其删除(可以使用std :: unique_ptr使其自动执行)。


now I see you could move struct args thread_args; 现在我看到您可以移动struct args thread_args; to Class1 - same as object2 . Class1object2相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM