4

Just a quick question. I have a network C application (TCP server) which has multiple worker threads(Pthreads). Each worker thread uses a select system call and each thread has the listening socket descriptor added to its select set. So effectively, each worker thread listens for incoming connections, and only one thread at a time succeeds in accepting the particular connection and that connection's socket descriptor is added to the respective thread's select set.

My question is that each thread has its own select set; is it possible that I can send or receive data to a client whose socket descriptor is in another worker thread's select set? In other words, can I use a socket descriptor from any worker thread's select set to perform I/O from any thread I want?

Jonathan Leffler
759k145 gold badges961 silver badges1.3k bronze badges
asked Apr 22, 2012 at 20:18

1 Answer 1

5

You can share sockets and file descriptors between different threads. That's what most servers do.

answered Apr 22, 2012 at 20:32
Sign up to request clarification or add additional context in comments.

7 Comments

Sorry for double checking:/ This means that if a thread accepts a connection and the returned file descriptor is added to other threads select set they will all be able to write/read from that descriptor right?
AFAIK, yes, it should make no difference in which thread the FD was created / accepted.
@Abdullah It is ok to use same sockets in different threads however you should probably make sure that read/write socket from one thread at time to avoid possible interleaving of data.
@Yusuf - yes :)
@Yusuf - fork(), which is used to create a new process, also copies the file descriptors, and is usually used by server to create worker processes. See the man page: man7.org/linux/man-pages/man2/fork.2.html
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.