I have an method in my application which is called by a third-party app by every 1 second. In my method I have to do some intensive math operations as well as persist data. Because I have to do the math operations in the one second period I'm creating a thread that will handle the file operations (as there are no hurry for these). My question is how should I pass the data to my file saving thread? The data is in shared_array<double> so should the data be passed by value or by reference? My code looks like as follows:

 

 

void workerMethod() {

    // do some mathematics

     shared_array<double> data = ....

     thread saveThread(bind(&DataFileSaver::saveInThread, dataFileSaver,data));

    // Thread is not joined

  }

 

I think that if I pass by reference the data variable can go out of scope and my thread can end up saving garbage. Am I correct?

 

My second question is that in my saveInThread method I'm using scoped_lock to guard the file operations. When I run some unit tests for this method I'm experiencing crashes and memory leaks. This is probably because I'm not joining the started thread in the workerMethod but in my unit tests I use sleep() enough so that the threads should have performed the operations. What am I doing wrong?