1

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!

0

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Why does it metter if the variable is on the stack or on the heap when I pass it to the thread ?
variable on stack gets deallocated when going out of scope, since you have thread accessing the shared variable, this should be from heap
Thanks, that will sure help me in the future! :)
@Dr.DebasishJana So, where is the memory freed?
2

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.

Comments

2

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.

2 Comments

I have to use array, as I'm using it to record audio and store the buffer there.
You can do most things with vectors that you can do with arrays. One of the only differences is that when growing the buffer, the entries of a vector are initialized, which can be a bit slower, but with better predictable behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.