Amit
Amit

Reputation: 703

Passing array to a thread

I've been trying to pass a short int *, an array of short ints to an std::thread, but the array is somehow corrupted, or not passing right into the thread..

Why is that? the name of the array is a pointer to the first cell, so I guess it is being passed by reference, right ?

Here is my code :

    short int waveIn[NUMPTS];
     // doing sutff with the array
    std::thread t1(toString, waveIn);
t1.detach();

and the thread function :

void toString(short int *waveIn)
{

  //    doing stuff with the array
}

But all the array cells are -1308, where I checked before passing the array into the thread, the array cells where somethnig else...

What is my problem?

Thanks!

Upvotes: 1

Views: 1056

Answers (3)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Instead of

short int waveIn[NUMPTS];

use dynamic allocation as:

short int *waveIn = new int[NUMPTS];

And after the hild thread(s) are detached, don't forget to deallocate, as:

delete [] waveIn;

Upvotes: 2

stefaanv
stefaanv

Reputation: 14392

You pass a pointer to a local array, which is freed when leaving the scope. So the memory of that array can be reused before the thread accesses it.

You can copy the data of the array to a std::vector (or use the std::vector to start with) and move that to the thread. This way the data will remain until the thread disposes of the vector.

Upvotes: 2

Peter G.
Peter G.

Reputation: 15114

The array waveIn is a local variable and probably is out of scope (so its space on stack will have been reclaimed for other purposes) when the thread t1 tries to use it.

Upvotes: 2

Related Questions