1

I am trying to pass multiple arrays to threads that are created using std::thread as follow:

threadPool.push_back(std::thread(factor, Ap, Ai, Ax, b, Rs, Q, P, Pinv, n, 0, n, scale, nz));

and the function factor is defined as the following:

void factor(int Ap[], int Ai[], double Ax[], double b[], double *Rs, int *Q, int *P, int *Pinv, int n, int k1, int k2, int scale, int nz);

The thread is created successfully and I can see it in the visual studio threads window (from the debugger). However, the data of the arrays in the thread are not similar to the data sent to the thread. Any one has any idea what could be the reason ?

Anas
  • 359
  • 1
  • 5
  • 14
  • 1
    Sounds like you passed a pointer (which is essentially what an array parameter is) which pointed to a function-scoped array, then exited the function so the array went out of scope and was destroyed. – Sneftel Apr 03 '15 at 13:38
  • Yes, the parameters (Ap, Ai, Ax and b) are initially defined as pointers and then passed to the function factor as arrays. Can you please explain further your above comment. – Anas Apr 03 '15 at 13:42
  • Use the same solutions as http://stackoverflow.com/questions/4264304/how-to-return-an-array-from-a-method – Sneftel Apr 03 '15 at 13:43

1 Answers1

1

Whenever you pass data to a thread (which is more heavily true for pointer typed data), you must make sure that the data remains intact while the thread is working on it.


You see if you pass a (function)local array to your thread, but the caller function finishes before your thread accesses your variable, the variable runs out of its scope and gets released, therefore there is no guarantee that it will contain its original value. The solution in non-managed environments is to protect your calling routine from finishing before your thread gets hold on the data. Also your thread should obtain ownership over your data.

The easiest solution to your problem is the following:

  1. Create a (!!! volatile!!!) boolean flag, unset it (=false) and pass it (by reference) to your thread.
  2. Block the execution of your main thread while your flag becomes set (=true).
  3. Make a copy of your arrays in your thread, then set your (volatile) flag(=true).

You can use other synchronization objects to wait for your thread to obtain ownership over the object. If you are on Windows platform for example, you can create an Event, pass it to your thread and wait for it without an infinite loop putting weight on your processor core.

mg30rg
  • 1,311
  • 13
  • 24