Click to See Complete Forum and Search --> : Blocking sockets


kim24dc
January 26th, 2005, 03:56 PM
I was wondering how blocking sockets (TCP) work when you do a send and receive at the same time. Specifically I was wondering about the 2 cases below:

1) There are two threads. The first thread is pending on a recv() call on the socket and no messages are coming in. The second thread needs to send a message on the same socket. Can the second thread send a message while the first thread is pending on the receive? Is this all transparent to the application layer?

2) If 1) is true, is it possible for a send to get pre-empted in the middle if a message is received, while the send is taking place? If so, does this cause any errors in send or recv?

In general, is there any possiblities of socket or data collisions when trying access the same socket in multiple threads?
Thanks

Mathew Joy
January 27th, 2005, 12:16 PM
One thing you have to understand is a TCP connection is bidirectional. That means data can be send and received at the same time. How ever this won't happen exactly that way in a single medium. Data going in opposite directions can't be passed on a wire. In other words you can issue a call without worring that the other has actually completed.

Winsock is thread safe. But when using a socket on multiple threads, you have to take the same precaution as you would take on a shared global resource. Said that, calling a recv() on one thread and send() on a different one on a same socket is considered to be safe. However you have to take care while issueing 2 recv() or two send() on 2 threads.

You may also wan't to note that when the call to blocking send returns, the actual send may not have taken place.