c++ - 线程更新类对象

标签 c++ multithreading visual-studio-2010 visual-c++

如何从线程返回一个类对象或如何持久化它的状态?

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 对象上调用一个方法,以便使用边缘权重和 dstMesh 更新 msmoother 对象。 dstMesh 与线程功能完美更新。为了在 msmoother 对象上执行 computeEnergy,对象应该返回到主线程或者它的状态应该被持久化。但它将能量返回为“0”。我怎样才能做到这一点?

最佳答案

内存在线程之间共享,因此它们对共享数据所做的所有修改最终都变得可见,无需任何额外的努力(返回保留 某些东西)。

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

关于c++ - 线程更新类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654663/

相关文章:

c++ - 计算机缺少 MSVCP100D.dll 文件

c - Pthreads 在循环完成之前返回,工作似乎在后台继续

visual-studio-2010 - 调试 Visual Studio 扩展性能问题

python - 如何使用线程池做死循环功能?

c# - 创建和运行测试

visual-studio - 防止 Visual Studio 尝试在 PDF 文件中作为二进制数据进行搜索

c++ - 在cpp文件中实现非模板类的模板成员

c++ - 如何向静态库添加分析编译?

c++ - 使用 Cocos2d-x api 在 Android 上打开文件

multithreading - 有办法取消 “AsyncWaitHandle.WaitOne()”吗?