In order to make two objects, Player 1
and Player 2
, of a class Player
sending and receiving messages, I implemented a blocking queue to synchronize the messages. This is the code I used:
class Message
{
public:
Player* sender;
std::string text;
};
template <typename T>
class BlockingQueue
{
public:
void push(const T& val)
{//code}
T pop()
{//code}
};
class Player
{
BlockingQueue<Message > queue;
public:
void sendMessage(const string& message, Player *dest)
{
Message msg;
msg.sender= this; // sender
msg.text = message;
dest->queue_.push(message);
};
void run()
{
while (true)
{
Message msg= queue_.pop();
// do something with the message
sendMessage("somehing",msg.sender);
}
}
};
int main()
{
Player player1("player1");
Player player2("player2");
thread thread1([&](Player* player) { player->run(); }, &player1);
thread thread2([&](Player* player) { player->run(); }, &player2);
player2.sendMessage("Hi",&player1); // send message to player2 (from player 1)
thread1.join();
thread2.join();
return 0;
}
what I did here ! is send messages between the two objects of class Player
through one single process.
How Can I have every player
in a separate C++ process?
Aucun commentaire:
Enregistrer un commentaire