如何在 class 中使用线程?
How do I use threading in a class?
我正在尝试为我的 OpenGL 项目创建一个加载屏幕,并且已阅读该内容以使其正常工作最好使用线程。我试图用我的线程调用我的函数,但我不断收到这些错误:
error C2064: term does not evaluate to a function taking 3 arguments
IntelliSense: no instance of constructor "std::thread::thread" matches the argument list
argument types are: (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;
}
您需要给 std::thread(Function &&f, Args&&... args)
一个 Lambda 或函数指针。
改变
std::thread first(LoadingScreen::LoadNewScreen,playScreen, true, true);
到
std::thread first(&LoadingScreen::LoadNewScreen,playScreen, true, true);
或者 Lambda,如果您需要对 this
指针的引用。
您需要传递一个附加参数,该参数是 class 的实例,其成员函数作为第一个参数传递。
std::thread first(&LoadingScreen::LoadNewScreen, this, playScreen, true, true);
// ^^^^ <= instance of LoadingScreen
需要附加参数,因为这是实际调用 LoadNewScreen
的参数。
this->LoadNewScreen(playScreen, true, true);
我正在尝试为我的 OpenGL 项目创建一个加载屏幕,并且已阅读该内容以使其正常工作最好使用线程。我试图用我的线程调用我的函数,但我不断收到这些错误:
error C2064: term does not evaluate to a function taking 3 arguments
IntelliSense: no instance of constructor "std::thread::thread" matches the argument list argument types are: (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;
}
您需要给 std::thread(Function &&f, Args&&... args)
一个 Lambda 或函数指针。
改变
std::thread first(LoadingScreen::LoadNewScreen,playScreen, true, true);
到
std::thread first(&LoadingScreen::LoadNewScreen,playScreen, true, true);
或者 Lambda,如果您需要对 this
指针的引用。
您需要传递一个附加参数,该参数是 class 的实例,其成员函数作为第一个参数传递。
std::thread first(&LoadingScreen::LoadNewScreen, this, playScreen, true, true);
// ^^^^ <= instance of LoadingScreen
需要附加参数,因为这是实际调用 LoadNewScreen
的参数。
this->LoadNewScreen(playScreen, true, true);