How to use C++11 thread with instance method?

Viewed 20079

I have a Class Player, and some sub-Class Player1, Player2, Player3 extends Player using C++.
Class Player have a method "run", and all of Player1,2,3 will override "run" to do different things.

class Player {
public:
    virtual void run();
}
class Player1: public Player {
public:
    void run();
}

In "main" function I will create some instance of Player1,2,3
and some C++11 thread call method "run" of these instance.

int main() {
    Player1 player1;
    Player2 player2;
    Player3 player3;
    Thread thread1(player1.run, this);
    Thread thread2(player2.run, this);
    Thread thread3(player3.run, this);
    thread1.join();
    thread2.join();
    thread3.join();

    return 0;
}

I have tried and I know it doesn't work,
so I try to use another function to call instance method.

function doRun1(Player1 player){
    player.run();
}

int main() {
    Player1 player1;
    Player2 player2;
    Player3 player3;
    Thread thread1(doRun1, player1);
    Thread thread2(doRun2, player2);
    Thread thread3(doRun3, player3);
    thread1.join();
    thread2.join();
    thread3.join();

    return 0;
}

This way seems to solve problem, but I have to create doRun1, doRun2, doRun3.... lots of function,
because the parameter of doRun1,2,3 need to be declare which is Player1,2 or 3

I can't think any better solution, can someone help me @@?

2 Answers
Related