How to run a non-static function in a new thread in C++

invalid use of non-static member function thread
thread with non static member function
c thread member function
std::thread
static assertion failed std::thread arguments must be invocable after conversion to rvalues
std::thread static member function
std thread call member functions
std thread object function

I am trying to code a basic game in C++. I have a class called player with a function called moveLeft(); which constantly monitors the "a" get that I want to run in a separate thread.

Calling it how I thought I was supposed to. I now understand that this is because it's a non-static function, but I'm unsure of how to do this now. I am using the <thread> library.

Player class
#pragma once
class player
{
    public:
        player(); // Constructor
        ~player(); // Destructor

        void moveLeft();
        void moveRight();
        void jump(double);

        int getHealth();

        double get_x_position();
        double get_y_position();

        double get_x_momentum();
        double get_y_momentum();

        bool getGrounded();

        void setHealth(int);

        void set_x_position(double);
        void set_y_position(double);

        void set_x_momentum(double);
        void set_y_momentum(double);

        void setGrounded(bool);

    private:
        int health;

        bool grounded;

        double x_position;
        double y_position;

        double x_momentum;
        double y_momentum;
};
moveLeft() function
void player::moveLeft()
{
    while (true)
    {
        while (GetKeyState(97))
        {
            if (grounded)
            {
                x_momentum -= .01;
            }
            else
            {
                x_momentum -= 0.07;
            }

            x_position += x_momentum;
        }
    }
}

How I thought I was supposed to set it up.

thread t1(&player::moveLeft);
t1.detach();

If you are starting the thread from a member function of your class, you are probably looking for

thread t1(&player::moveLeft, this);
t1.detach();

The reason for including the this pointer is that every member function has a hidden parameter, the pointer to the object with which it is associated. this in the code above is a player*. Of course, you can use any other pointer to player, not necessarily this. Whatever object you point to, the member function will see it as "this object" inside its body.

C++11 : Start thread by member function with arguments , Starting thread with non static member function​​ void execute(std::string command); }; Now we want to start a thread which uses execute() function of the class Task as thread function. As execute() is a non static function of class Task, so first of all we need a object to call this function. Now we want to start a thread which uses execute() function of the class Task as thread function. As execute() is a non static function of class Task, so first of all we need a object to call this function. Let’s create an object of class Task i.e.

If you want to do it that way, you need to create an instance of the player class

player *myplayer = new player(); //do this in your initializer, not for every call.
thread t1(&player::moveLeft, myplayer);
t1.detach();

The singleton approach posted in another reply will work if you only want one instance of a player.

Calling a non-static member function as a thread function , This article describes how to call a C++ class member function as a I am going to present a new way to call a non-static member function. Steps to create a thread in a C# Program: First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime. Now, create and initialize the thread object in your main method.

Start a thread of a non-static member function workaround C++, The function of the class needs to use the 'this' keyword to access the values of those instances. You want to call this function as a new thread. You get the error​  Hi, Try this, Very easy, and wil run each function in a pool thread, Look for QtConcurrent in dicumentation. @ #include <QtConcurrent> void MainWindow::on_pushButton_clicked()

You can use std::bind to solve this problem.

thread t1(std::bind(&player::moveLeft,this));
t1.detach();

Non-static member functions - cppreference.com, Thread support library (C++11) class S { int mf1(); // non-static member function declaration void mf2() volatile, mf3() && Calling a member function of class X on an object of any other type invokes undefined behavior. In main() we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread. pthread_create() takes 4 arguments. The first argument is a pointer to thread_id which is set by this function.

C++ Tutorial: Static Variables and Static Class Members, Static objects are destroyed when the program stops running. Non-static member functions can access all data members of the class: static and non-static Dynamic memory is controlled by the new and delete operators, not by scope and linkage rules Multi-Threaded Programming III - C/C++ Class Thread for Pthreads The starting function for both the threads is kept same. Inside the function ‘doSomeThing()’, the thread uses pthread_self() and pthread_equal() functions to identify whether the executing thread is the first one or the second one as created. Also, Inside the same function ‘doSomeThing()’ a for loop is run so as to simulate some time consuming work.

C++ Programming HOW-TO: Threads in C++, 18. Threads in C++. IBM pthread User Guide, Thread concepts, API reference the static function. The static function will then typecast the void * and use it to call a non static member function. To use the thread class, you derive a new class. Now we want to pass this member function Task::execute() as thread function in pthread_create(). As pthread_create() accepts a function pointer as an argument of following type i.e. So, typecast Task::execute with type. Also, as compiler pass the pointer of class (this pointer) as first argument in every member function.

Difference between static and non-static method in Java , Every methods in java are non-static method, but the methods must not have static p.show();. Parent c = new Child();. // calling Child's show(). c.show();. }. Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. The thread begins executing at the first line of the method represented by the ThreadStart or ParameterizedThreadStart delegate supplied to the thread constructor. Note that the call to Start does not block the calling thread.

Comments
  • use static function to start the thread and pass player as an argument to it: thread t1(&run, player); in the run function call player->moveLeft().
  • Thank you! But now when I run it I get this error "E0258 'this' may only be used inside a nonstatic member function"
  • So you are launching the thread from a static member function? These functions don't see the this pointer, they are like global functions in the class namespace. It won't work this way. You might need to re-evaluate your program architecture.
  • Thank you. Sorry I know my code isn't the best. I just started to learn about classes and objects so it'll take me a little while to get the hang of it.
  • @diego_rod: No need to apologize - we get that on StackOverflow all the time. The important thing is that you ask questions properly (which you seem to have), not that you be experienced or have good code and good design.
  • The use of std::bind is essentially deprecated with the advent of lambda's.
  • Thank for your reminder. So let's use the lambda to handle it. thread t1([&]() { player.moveLeft(); } ); t1.detach();
  • std::bind() is not necessary, the constructor of thread can take the this parameter directly.