views:

48

answers:

2

Hi All, Is it ok to use same socket fd in multiple threads ? (over linux)

+2  A: 

It depends on what you expect to happen, but yes you can. If you are reading UDP packets that are each a complete message this can work well. If you are reading data streams from TCP this will probably not work well.

You can have multiple threads accepting incoming connections on a socket and that can work pretty well as each thread gets one connection.

Zan Lynx
A: 

You will run into concurrency problems trying to send() or recv() (SOCK_STREAM) from multiple threads. You should use a critical section or some other means of creating serial access to send() and recv().

One standard thing to do with threads is to have the master listen() & accept(), then pass off the socket to a client thread that sends/receives/processes from that one socket. The client thread is responsible for calling close() or shutdown().

jim mcnamara