you can't, it is gone when the workerFunc() exits.
if you need access to it from outside the thread, either make the array global, or make it local to the thread that starts the worker thread and pass it aloong into the worker thread. If you can guarantee that your main thread won't ever access the array until the worker thread is finished, that's all you need.
If your main thread needs to access the array while the thread is running, you will need to provide proper synchronization.
Allocate the array in main instead and pass a pointer/reference to it to the workerFunc
Last edited by S_M_A; November 22nd, 2012 at 11:06 AM.
Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it.
- Brian W. Kernighan
Another possibility is to use a future to return a value from the thread function. This will not work with a static array, because you cannot return a static array from a function, but it will work with pretty much anything else.
See the example in the boost documentation: http://www.boost.org/doc/libs/1_52_0...tures.creating
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Thank you, I didn't realise it was that straight forward!
Here is the code in case anyone else needs to do something similar:
The flaw in your function is that anyone can pass a smaller array, and that function would not detect it.
Code:
void workerFunc(int start, int a[5]){
That definition does not ensure that the array is of 5 elements. In C++, arrays decay to pointers. The definition above is the same as this:
Code:
void workerFunc(int start, int* a)
If I passed an array of 2 elements instead of 5, your function would still go through and process 5 items, causing undefined behaviour. This is the flaw of using "simple and dumb" arrays -- there is no bounds checking. Instead, proper usage of container classes (i.e. std::vector<int>) would be appropriate.
Bookmarks