如何线程函数
How do I thread a function?
初学者的问题,但是如何线程?
我有此代码段:
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);});
确实要注意捕获通过参考或值
作为旁注,请确保您的程序中没有数据竞赛
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- C++使用params创建线程函数会导致转换错误
- 为什么std::async使用同一个线程运行函数
- 使用 std::string () const 函数启动线程或未来
- C++线程中,没有重载函数接受 X 参数
- 如何从线程中的不同模块调用函数?
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 如何将类的成员函数传递给线程
- 是否可以创建一个从不同类调用函数的线程?
- 如何制作一个只能在一个线程上同时执行的函数?
- 启动类函数作为失去引用的线程
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 非静态成员失败的线程调用函数
- 线程调用的函数对对象删除是否安全?
- 将类成员函数作为线程调用到另一个类成员函数时发出警告消息
- 类成员在构造函数(线程)之后更改地址
- C++无限依次运行两个函数(线程)
- c++将各种参数传递给父类构造函数(线程c++11)