MrB
MrB

Reputation: 83

Separate threads for socket send/recv?

I'm weighing up how to implement a TCP based server (in C) - the server will accept a connection from a client, receive commands from the client, and then send the response. Pretty simple stuff - but the processing of the command must be done by another thread in the system, which introduces a bit of concurrency to the mix.

So I'm trying to decide whether to handle all TCP comms in one thread, using non-blocking sockets and select(), or to use blocking sockets and two separate comms threads (one for sending, one for receiving).

My concern about the latter is handling socket synchronisation - if I close the socket in the send thread, what happens in the receive thread (or vice versa) .. and how to deal with this and clean up in the correct manner.

Any advice would be much appreciated.

Upvotes: 4

Views: 3320

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597941

You do not need separate receive and send threads for a client. When the client is accepted, create one thread that handles all of the I/O for that client, both receiving and sending (especially since you are implementing a command/response protocol). But if you do choose to use separate threads, closing a socket in one thread will cause detectable errors in the other thread that is using the same socket. Simply terminate each thread when a socket error occurs, and then decide which thread is going to be responsible for closing the socket.

However, if you need to handle a high number of concurrent clients then threading is not the best choice. Asynchronous I/O using non-blocking sockets (or on Windows, using I/O Completion Ports) is better, as it requires a smaller number of threads.

Upvotes: 5

Related Questions