Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++11 thread with instance method? [duplicate]

Tags:

c++

c++11

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 @@?

like image 876
Azure Chen Avatar asked Dec 14 '13 17:12

Azure Chen


1 Answers

You are looking for something like this...

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

class Player1: public Player {
public:
    void run(); // you must implement then for Player1, 2, 3
};

void doRun(Player * player)
{
    player->run();
}

int main(int argc, char * argv[]) {
    Player1 player1;
    Player2 player2;
    Player3 player3;

    thread thread1(doRun, &player1);
    thread thread2(doRun, &player2);
    thread thread3(doRun, &player3);

    thread1.join();
    thread2.join();
    thread3.join();

    return 0;
}

If you prefer, you can also use lambda expressions:

int main(int argc, char * argv[]) {
    Player1 player1;
    Player2 player2;
    Player3 player3;

    thread thread1([&] (Player * player) { player->run(); }, &player1);
    thread thread2([&] (Player * player) { player->run(); }, &player2);
    thread thread3([&] (Player * player) { player->run(); }, &player3);

    thread1.join();
    thread2.join();
    thread3.join();

    return 0;
}

Or, following DyP suggestion:

int main(int argc, char * argv[]) {
    Player1 player1;
    Player2 player2;
    Player3 player3;

    thread thread1(&Player::run, player1);
    thread thread2(&Player::run, player2);
    thread thread3(&Player::run, player3);

    thread1.join();
    thread2.join();
    thread3.join();

    return 0;
}
like image 127
Wagner Patriota Avatar answered Nov 04 '22 11:11

Wagner Patriota