1

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?

László Papp
  • 51,870
  • 39
  • 111
  • 135
TSG
  • 4,242
  • 9
  • 61
  • 121
  • You should declate your mutex in same scope with socket member. – Dmitry Sazonov Oct 03 '13 at 08:39
  • 1
    If you want one mutex per socket, pair one with each socket – Frank Osterfeld Oct 03 '13 at 09:16
  • I don't understand how. Based on my reading, if I declare a socket variable at the class level, and a mutex at the class level, then all threads (of that class) share the same mutex which is not what I want. – TSG Oct 03 '13 at 16:04

1 Answers1

0

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.

László Papp
  • 51,870
  • 39
  • 111
  • 135