Reading from 2 sockets on 2 streams results in data loss

I have a multithreaded C ++ windows application written in Visual Studio 6.

In Appendix 2, threads are each started trying to read UDP packets on different ports. If I protect the read from the socket with a critical section, then the entire date read is fine. Without this protection, data is lost from both sockets.

Is reading from a socket unsafe? I have written many socket applications in the past and do not remember using such thread protection.

0


source to share


4 answers


There are 2 streams running in the application, each of which tries to read UDP packets on different ports.

How much UDP data are you sending / reading? How fast do you send it? How much of your data is lost?

It could be a race condition ... Not between two threads, but between a thread and a socket!



I've seen problems in the past in porting code from Linux to Windows. Windows uses (uses) UDP buffering by default, which is 8k. Naturally we were sending in 12kg bursts and it just wasn't possible to read them fast enough even with a special read thread!

You can change UDP buffering (under Windows) with something like:

int newBufferSize = 128 * 1024;  // 128k
setsockopt( readSocketFd, SOL_SOCKET, SO_RCVBUF, (char *) & newBufferSize );

      

+2


source


Winsock does not guarantee thread safety. It's up to the performer. Take a look here .



+1


source


Reading from one socket on two threads is not thread safe, you may not know for sure which caller is receiving the packet from the main socket buffer. Writing to a socket is the same. Since you are reading two different sockets on two different threads (and I am assuming each socket has its own thread), it should work.

0


source


Are you sure you are not reading from the same socket? In our system, we use exactly this: 2 linked UDP sockets + 2 streams to read from them. No problem and no need for synchronization.

0


source







All Articles