【问题标题】:How do I use threading in a class?如何在课堂上使用线程?
【发布时间】:2015-02-18 09:30:50
【问题描述】:

我正在尝试为我的 OpenGL 项目创建一个加载屏幕,并且已经阅读了它以使其正常工作,最好使用线程。我试图用我的线程调用我的函数,但我不断收到这些错误:

错误 C2064:术语不计算为采用 3 个参数的函数

IntelliSense:没有构造函数“std::thread::thread”的实例与参数列表匹配 参数类型有:(void (Screen* newScreen, bool activeVisuals, bool activeControls), PlayScreen *, bool, bool)

这是我的代码:

//LoadingScreen
class LoadingScreen
{
    LoadingScreen();
    void LoadNewScreen(Screen* newScreen, bool activeVisuals, bool activeControls);
    void Setup();
};

void LoadingScreen::LoadNewScreen(Screen* newScreen, bool activeVisuals, bool activeControls)
{

}

void LoadingScreen::Setup()
{
    PlayScreen *playScreen = new PlayScreen();
    std::thread first(LoadingScreen::LoadNewScreen,playScreen, true, true);// , playScreen, true, true);

    first.join();
}

//source.cpp
LoadingScreen loadingScreen;
int main()
{
    LoadingScreen loadingScreen = LoadingScreen();
    loadingScreen.Setup();

    return 0;
}

【问题讨论】:

  • 在执行此操作时,请确保您了解线程如何与 OpenGL 一起使用。我不知道您正在加载什么样的资源,但如果您使用共享资源或映射/取消映射缓冲内存的多个渲染上下文,您可能会遇到 CPU/GPU 同步问题。
  • @AndonM.Coleman 是的,我似乎无法让线程工作。它不断抛出我找不到任何信息的异常,例如: [程序名称] 0xC0000005 中 0x00E9E2C9 处的未处理异常:访问冲突写入位置 0x00000020。

标签: c++ multithreading opengl


【解决方案1】:

您需要传递一个附加参数,该参数是其成员函数作为第一个参数传递的类的实例。

std::thread first(&LoadingScreen::LoadNewScreen, this, playScreen, true, true);
                                             //  ^^^^ <= instance of LoadingScreen

需要附加参数,因为这实际上是调用LoadNewScreen

this->LoadNewScreen(playScreen, true, true);

【讨论】:

  • @LightnessRacesinOrbit 好吧,您不一定需要传递指针,但在这种情况下,是的。
  • 这样就可以编译了。谢谢你的回答。为什么它需要额外的实例?
  • @WhyYouNoWork 因为这就是所谓的 LoadNewScreenthis-&gt;LoadNewScreen(playScreen, true, true);
  • 我现在明白了。谢谢你的澄清
  • 我不喜欢答案中的“附加实例”术语;我认为它误导了WhyYouNoWork!
【解决方案2】:

您需要给 std::thread(Function &amp;&amp;f, Args&amp;&amp;... args) 一个 Lambda 或一个函数指针。

改变

std::thread first(LoadingScreen::LoadNewScreen,playScreen, true, true);

std::thread first(&LoadingScreen::LoadNewScreen,playScreen, true, true);

如果您需要对 this 指针的引用,也可以使用 Lambda。

【讨论】:

  • 我在回答之前试过这个。它导致我列出的第一个错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 2019-07-03
  • 2019-05-13
  • 2015-03-31
  • 2015-06-29
相关资源
最近更新 更多