Niklas Utterback
Niklas Utterback

Reputation: 349

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.

Upvotes: 0

Views: 85

Answers (3)

Passer By
Passer By

Reputation: 21131

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

Upvotes: 0

Sinapse
Sinapse

Reputation: 792

Assuming myScene to be of type Scene try this:

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

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249103

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).

Upvotes: 4

Related Questions