Reputation: 605
How to return a class object from threads or how to persist its state?
struct DataStructure
{
MapSmoother *m1;
std::vector<Vertex*> v1;
std::vector<Vertex *>::iterator vit;
DataStructure() {
m1 = NULL;
v1;
vit;
}
};
DWORD WINAPI thread_fun(void* p)
{
DataStructure *input = (DataStructure*)p;
for( ; (input->vit) != (input->v1).end(); ){
Vertex *v = *input->vit++;
(*(input->m1)).relax(v);
}
return 0;
}
main()
{
//Reading srcMesh
//All the vertices in srcMesh will be encoded with color
MapSmoother msmoother(srcMesh,dstMesh); //initial dstMesh will be created with no edge weights
DataStructure* input = new DataStructure; //struct datatype which holds msmoother object and vector "verList". I am passing this one to thread as a function argument
for(int color = 1; color <= 7 ; color++)
{
srcMesh.reportVertex(color,verList); //all the vertices in srcMesh with the same color index will be stored in verList datastructure(vector)
std::vector<Vertex *>::iterator vit = verList.begin();
input->vit = vit;
for(int i = 0; i < 100; i++)
HANDLE hThread[i] = createThread(0,0,&thread_fun,&input,0,NULL);
WaitForMultipleObjects(100,hThread,TRUE,INFINITE);
for(int i = 0; i < 100; i++)
CloseHandle(hThread[i]);
}
msmoother.computeEnergy(); // compute harmonic energy based on edge weights
}
In thread_fun, i am calling a method on msmoother object in order to update msmoother object with edge weights as well as dstMesh. dstMesh is updated perfectly with thread function. In order to perform computeEnergy on msmoother object, object should be returned to main thread or its state should be persisted. But it returns energy as '0'. How can i achieve this?
Upvotes: 1
Views: 121
Reputation: 1689
If computeEnergy() requires all threads to have completed you can pass the handle to each thread to a WaitForMultipleObject which supports waiting for threads to complete. Within each thread you can add or modify a value within the msmoother
object (as passed by pointer to thread_fun
).
The msmoother
object will live until the threads all return so passing a pointer to it is acceptable.
Upvotes: 1
Reputation: 21517
Memory is shared between threads, so all modification they make on shared data eventually become visible without any additional effort (to return or persist something).
Your problem is, apparently, that you don't wait for threads to complete before attempting to use data they should have prepared. As you already have an array of thread handles, WaitForMultipleObjects
should be a convenient way to wait for all threads' completion (notice bWaitAll
parameter). Note that WaitForMultipleObjects can't wait for more than 64 objects at once, so you need two calls if you have 100 threads.
Upvotes: 2