PDA

View Full Version : QTcpSocket - write to socket from several threads



Einat
7th November 2013, 14:01
I am writing a client server application using QTcpSocket.

Two questions:

1. My application is multi-threaded and several threads may call to socket.write() method.
Should I protect calling to write method (using Mutex) or QIODevice::write is MT safe ?

2. If we read and write to the same socket , do we need to lock in application level or does TCPSocket already handles that ?

Thanks.

anda_skoa
7th November 2013, 14:37
QTcpSocket does not provide any locking itself, that would be wasteful in single threaded usage cases (which is almost always the case).

If I were you I would really avoid accessing the socket from multiple threads.
For example if your threads assemble messages that need to be sent, let them emit the message in a signal and let the thread owning the socket send them.

Cheers,
_

Einat
8th November 2013, 06:11
Thanks a lot for your reply.

I absoultly agree that writing to the socket should be done from a single thread.

What about reading and writing to the sokcet from different threads ? One thread read while the other thread write ?

Thanks.

wysota
8th November 2013, 07:45
What about reading and writing to the sokcet from different threads ? One thread read while the other thread write ?
There is really no reason to do that. Reading from a socket is not a time consuming operation - you can read from the socket and emit a signal with the data read. The signal can be caught from any thread you want.