I have a class Class1
with a method Class1::Run
that is called sequentially. 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
:
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.
The ThreadHelper
function has been declared as static
inside Class1
and it is structured as follows:
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?
The problem is that you pass to thread a pointer to local variable 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).
now I see you could move struct args thread_args;
to Class1
- same as object2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.