I am working on a simple 1v1 (realtime) brick breaker game, in order to improve my programming skills.
It is based on the server-client model and I am using <winsock2.h>
, <thread>
and <mutex>
libraries for implementation.
On the client side, I would like to call the send() and recv() functions from different threads (send() from the main() thread, while recv() from another one).
I've realized, it would be the best if the recv() function was blocking, while send() non-blocking.
I've heard that creating a socket like this in winsock2 is not possible. However, I came up with an idea and would like to know, if it is a bad practice:
I connect to the server with a blocking socket. And when an important user event happens, I create a detached thread which calls the sender function (that hands the user's event to the server), instead of calling the sender method from the main thread.
With std::mutex
, I would be able to guarantee that only one sender method is working at a time. Example:
#include <mutex>
#include <string>
class Connection
{
std::mutex senderMutex
// other member variables
void sendMessage(std::string& msg)
{
std::lock_guard<std::mutex> lg(senderMutex);
// some code
}
void sendUserAction(Action& action)
{
std::lock_guard<std::mutex> lg(senderMutex);
// some code
}
// other member functions
};
From the main thread:
if (userEventHappened)
{
switch(userEvent)
{
case ChatMessage:
std::thread(&Connection::sendMessage, &connection /* an instance of Connection*/, std::ref(message)).detach();
break;
case UserAction:
std::thread(&Connection::sendUserAction, &connection, std::ref(action)).detach();
break;
}
}
Since it is a brick breaker game where the player have to move its own paddle, there are many user actions, thus too many threads can be created in a short time.
I'm curious, if it is dangerous and/or a bad practice to call the send() methods from detached threads, or is there a better solution.
It's also not clear to me, whether it causes performance issues that most of the threads are blocked by senderMutex
.