I need to protect a resource from being interrupted, in this case writing to a socket. I have a class, TelnetServer, which is instantiated many times (once per used connection).
I want to prevent a write to a single user from being interrupted by another write to that same user (i.e. locking the mutex for writes to that one socket). But, I don't want to freeze ALL writes to all sockets while I write to a single user. To clarify (pseudo c++):
Class TelnetThread {
QMutex mutex;
void writeToSocket() {
mutex.lock();
socket->write(string);
mutex.unlock();
}
}
So if I have 30 TelnetThread's running, writing to one socket should NOT prevent simultaneous writing to another thread. But, if a couple of slots trigger writes to the same socket/thread, then then they should be serialized.
Where should I declare my mutex variable? If I make it a class (thread) variable, won't that serialize all socket writes across all threads (all instances of this class)? If I make make it a function variable within writeToSocket, then I don't think it will serialize writes even to the same socket.
Help...how do I do this?
i.e. locking the mutex for writes to that one socket
You could either write an encapsulated socket write locker type, or just treating the mutex with the corresponding together within the same unit.
As I wrote in one of your previous threads, I would consider using QMutexLocker for such cases. It is less error-prone, and it also makes the code shorter.