Starting class functions as threads loosing reference

43 views Asked by At

i am working on a windows program, which does the hard work in threads and the GUI stays in the main loop (in this case i use ImGui OpenGL3)

but with implementing more functions, the parameters are getting out of scope when starting a work_thread and the function started by beginthread receives pointer showing to NULL (in fact not changing the code but including another library provokes that this happens)

what is going on and how to prevent this from happening

here a raw represantation of my code

#include <process.h>


class JOBS
{
public:
  void jobA(char *path);

};

void JOBS::jobA(char*path) {   . .     }


class APP_DATA
{
public:
  JOBS jobs;

public:
  char *path;
};



void job_a_threadstarter(void* pParams )
{
APP_DATA *app=*(APP_DATA **)  pParams;   

  app->jobs.jobA(app->path);  
}


void job_starter(APP_DATA *app)
{     
  _beginthread(job_a_threadstarter,0,&app);        
}



int main(int, char**)
{
APP_DATA app; 
char workpath[99]="path_to_somewhere";

    .
    .

  app.path=workpath;
  job_starter(&app);



    .
    .
}

usually the code runs with no problems, but some change in other routines and job_a_threadstarter is crashing as the pParams is referencing to NULL

i am using GNU G++ with mingw on a x64 Windows compiling with c++11 switch and linking with -mwindows

1

There are 1 answers

1
rafix07 On BEST ANSWER

You are passing pointer to local variable (app) which is destroyed when job_starter ends

_beginthread(job_a_threadstarter,0,&app); // you are getting pointer to local variable

replace it by

_beginthread(job_a_threadstarter,0,app); // forward pointer to app