2013-02-01 25 views
1

如何从线程返回一个类对象或如何保持其状态?线程更新类对象

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 
} 

在thread_fun,我打电话msmoother对象上的方法,以便更新与msmoother边权以及dstMesh对象。 dstMesh使用线程功能完美更新。为了在msmoother对象上执行computeEnergy,应该将对象返回到主线程或其状态应该保持。但它将能量返回为'0'。我怎样才能做到这一点?

回答

2

内存在线程之间共享,这样他们就共享数据的修改都没有任何额外的努力最终成为可见的(以坚持东西)。

你的问题显然是,你不要等待线程完成之前,试图使用他们应该已经准备好的数据。由于您已经有一个线程句柄数组,因此WaitForMultipleObjects应该是等待所有线程完成的便捷方式(请注意参数bWaitAll)。请注意,WaitForMultipleObjects不能一次等待超过64个对象,因此如果您有100个线程,则需要两次调用。

+0

打了我14秒......哦为什么你这么快就移动。因为我忘记提及100个物体的限制,所以请大声点赞。 – NtscCobalt

+0

实际上,在我调用computeEnergy方法之前,我调用了WaitForMultipleObjects和CloseHandle方法。我更新了代码。 – Hello

+0

@你好,你没有检查错误,并且每个等待中肯定有*超过64个(或63个)对象的错误。 –

1

如果computeEnergy()要求所有线程完成,则可以将句柄传递给支持等待线程完成的WaitForMultipleObject。在每个线程中,您可以添加或修改msmoother对象内的值(通过指针传递给thread_fun)。

msmoother对象将一直存在,直到线程全部返回,因此将指针传递给它是可以接受的。

+0

实际上,在调用computeEnergy方法之前,我调用了WaitForMultipleObjects和CloseHandle方法。我更新了代码。根据你的回答,我明白的是从工作线程返回后,对象将会在主线程中被保留下来吗?但为什么它不计算能量? – Hello

+0

@你好你真的在更新DataStructure吗?您在传递给'createThread'的指针时传递一个指针。您可能会修改不同的记忆集。 – NtscCobalt

+0

我更新了数据结构和线程函数的代码。请检查 – Hello