Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Threads Share the same Client Socket?

Im using TClientSocket or indy's TIdTCPClient (depending on project)

I have a few Threads each processing items, and sometimes need to send data over the connected client socket. (Data Read form the socket is NOT used in the processing threads)

Basically my question is...

  • Is the possible?
  • is it "safe"?

or should I

  • have a client socket per thread or
  • some kinda of Marshalling/critical sections

delphi-7 indy-9

like image 473
Christopher Chase Avatar asked Dec 10 '10 03:12

Christopher Chase


1 Answers

Multiple threads can read and write to the same socket. Since everytime you accept, it shall extract the first connection on the queue of pending connections, create a new socket with the same socket properties and allocate a new file descriptor for that socket.

So only one thread per accepted connection.

If you are asking if you can do multiple write/read on an accepted connection, you will need locking features, hence loss of parallelism benefits. If you want to thread a long process and then write the result in the socket, use synchronization to write in the correct order.

like image 90
Julio Guerra Avatar answered Oct 29 '22 09:10

Julio Guerra