Accessing array in a thread (boost)
I was wondering if it was possible to access data from an array inside a threaded function after it has finished executing?
Take this example:
Code:
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
void workerFunc(int start){
int arr[5];
int i;
for(i = 0; i < 5; i++){
arr[i] = start;
start++;
}
}
int main(){
boost::thread workerThread(workerFunc, 3);
workerThread.join();
return 0;
}
After workerFunc has finished, how could I access the array arr? Is there any way to get (3,4,5,6,7) back into main()?
Thank You :)
Re: Accessing array in a thread (boost)
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.
Re: Accessing array in a thread (boost)
Allocate the array in main instead and pass a pointer/reference to it to the workerFunc
Re: Accessing array in a thread (boost)
Thank you, I didn't realise it was that straight forward! :)
Here is the code in case anyone else needs to do something similar:
Code:
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
void workerFunc(int start, int a[5]){
int i;
for(i = 0; i < 5; i++){
a[i] = start;
start++;
}
}
int main(){
int arr[5];
boost::thread workerThread(workerFunc, 3, arr);
workerThread.join();
cout << arr[2];
system("pause");
return 0;
}
Re: Accessing array in a thread (boost)
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
Re: Accessing array in a thread (boost)
Quote:
Originally Posted by
SamstaUK
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.
Regards,
Paul McKenzie