如何在实例方法中使用C ++ 11线程? [英] How to use C++11 thread with instance method?
问题描述
我有一个Class Player,有些子类Player1,Player2,Player3使用C ++扩展了Player。
Class Player有一个运行方法,所有Player1,2,3都会覆盖运行以执行不同的操作。
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();
}
在 main函数中,我将创建一些Player1,2,3实例
和这些实例的某些C ++ 11线程调用方法运行。
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;
}
这种方法似乎可以解决问题,但我必须创建doRun1,doRun2, doRun3 ....很多功能,
因为需要声明doRun1,2,3的参数是Player1,2或3
我想不出更好的解决方案,有人可以帮我@@吗?
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 @@?
推荐答案
您正在寻找类似的东西这...
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;
}
如果愿意,还可以使用lambda表达式:
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;
}
或者,按照DyP的建议:
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;
}
这篇关于如何在实例方法中使用C ++ 11线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!