如何线程函数

How do I thread a function?

本文关键字:函数 线程 何线程      更新时间:2023-10-16

初学者的问题,但是如何线程?

我有此代码段:

std::vector<std::thread*> threads[8];
for (unsigned short rowIndex = 0; rowIndex < unimportantStuff.rows; ++rowIndex)
{
    for (unsigned short columnIndex = 0; columnIndex < unimportantStuff.columns; ++columnIndex)
    {
        myModelInstance = new CModelInstance;
        myModelInstance->Init(myLoader.CreateTriangle(myFramework.myDevice, { -0.8f + unimportantStuff.offset*columnIndex, -0.8f + unimportantStuff.offset*rowIndex }), { -0.8f + unimportantStuff.offset*columnIndex, -0.8f + unimportantStuff.offset*rowIndex });
        myScene.AddModelInstance(myModelInstance);
    }
}

如果可能的话,我想同时启动初始功能和AddModelInstance函数,但是我不知道该如何继续。如何激活多个线程(在这种情况下最多8个线程)?

我尝试了这样的单程:

std::thread t1(myScene.AddModelInstance, myModelInstance);

但是我会收到以下错误:

cscene :: addModelinstance':非标准语法;使用'&amp;'创建指向会员的指针

我尝试添加&amp;对功能和参数都没有工作。

而不是:

std::thread t1(myScene.AddModelInstance, myModelInstance);

您需要这样的东西:

std::thread t1(&Scene::AddModelInstance, myScene, myModelInstance);

&Scene::AddModelInstance是要调用的成员函数的指针,大概采用隐式this参数(myScene)。

假设myScene是类型Scene尝试以下操作:

std::thread t1(&Scene::AddModelInstance, &myScene, myModelInstance);

一种干净而直观的方法是使用lambda表达式

std::thread t1([&]() mutable {myScene.AddModelInstance(myModelInstance);});

确实要注意捕获通过参考或值

作为旁注,请确保您的程序中没有数据竞赛