tags:

views:

485

answers:

4

I have a multi-threaded Windows C++ app written in Visual Studio 6.

Within the app 2 threads are running each trying to read UDP packets on different ports. If I protect the reading from the socket with a critical section then all the date read is fine. Without that protection data is lost from both sockets.

Is reading from a socket not thread safe? I've written many socket apps in the past and don't remember having to use this sort of thread protection.

A: 

Reading from one socket in two threads is not thread safe, you may not know for sure which caller gets a packet fron the underlying socket buffer first. Writing to a socket is the same. Since you're reading from two different sockets in two different threads (and I assume that each socket has its own thread), it should work.

vividos
A: 

Are you certain that you're not reading from the same socket? In our system we're using exactly this: 2 bound UDP sockets + 2 threads to read from them. No problems and no syncing needed..

Marcin Gil
+1  A: 

Winsock is not guaranteed to be thread-safe. It's up to the implementer. Have a look here.

xtofl
+2  A: 

Within the app 2 threads are running each trying to read UDP packets on different ports.

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

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

I've seen problems in the past porting code from Linux to Windows. Windows uses (used) a default UDP buffersize of 8k. Naturally, we were sending 12k bursts, and there's just no way to read it fast enough even with a dedicated read thread!

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

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