简体   繁体   中英

How do I thread a function?

A beginner's question, but how do I thread?

I have this code snippet:

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);
    }
}

I want to thread both the Init function and the AddModelInstance function if possible, however I don't know how to continue. How do I activate multiple threads (up to 8 in this case)?

I tried with a single thread like this:

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

But I get the following error:

CScene::AddModelInstance': non-standard syntax; use '&' to create a pointer to member

I tried adding & to both the function and the argument, but neither worked.

Instead of this:

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

You need something like this:

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

&Scene::AddModelInstance is a pointer to the member function you want to call, which presumably takes an implicit this parameter ( myScene ).

假设myScene属于Scene类型,请尝试以下操作:

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

A clean and intuitive way is to use lambda expressions

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

Do take note about capturing by reference or value

As a side note, make sure you have no data races in your program

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM