Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use threading in a class?

I'm trying to create a loading screen for my OpenGL project and have read that to get it to work correctly it was best to use threading. I'm trying to call my function with my thread, but I keep getting these errors:

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)

This is my code:

//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;
}
like image 283
WhyYouNoWork Avatar asked Feb 18 '15 00:02

WhyYouNoWork


2 Answers

You need to pass an additional parameter which is an instance of the class whose member function was passed as the first argument.

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

The additional parameter is needed because this is what actually calls LoadNewScreen.

this->LoadNewScreen(playScreen, true, true);
like image 162
Axalo Avatar answered Oct 02 '22 23:10

Axalo


You need to give std::thread(Function &&f, Args&&... args) a Lambda or a Function Pointer.

Change

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

To

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

Or a Lambda if you need a reference to the this pointer.

like image 38
BlamKiwi Avatar answered Oct 02 '22 22:10

BlamKiwi