views:

358

answers:

3

I'm using winsock and calling connect on a non-blocking socket. I occasionally see some delay (up to 200ms) before the function returns when the CPU is hogged by other processes. From what I know, a connect on a non-blocking socket should return immediately, but perhaps connect causes a context switch and since the CPU is working hard it takes a while before my thread gets CPU time again and exits the function.

I know (or at least fairly certain) that connect on a blocking socket causes a context switch, but does connect on a non-blocking socket cause one?

A: 

A non-blocking call won't cause a context switch by it's very definition. However, a context switch could potentially immediately occur.

I'm not sure what you mean here. "From what I know, a connect on a non-blocking socket should return immediately." On the one hand, yes the subsequent lines of code will execute regardless of whether or not a connection completes so in that sense it will return immediately. If you mean that it will return immediately in that no context switch will ever occur before it returns you'd be incorrect.

Spencer Ruport
+1  A: 

A context switch is always possible at any moment, no matter whether it is non-blocking connect, blocking connect, or any time before/after connect. It is just that non-blocking connect may return when the connection process is not yet completed.

In any modern operating systems, context switching is possible within any stages your normal program is running. There are never any guarantee that a certain piece of code will be run uninterrupted. (only those very critical to the system would get such privilege)

billyswong
+1  A: 

Also, this call needs to go down to the kernel, which already means some time spent. And as others have pointed out: a context switch can occur at any time. You can do some tricks (like using a slightly higher priority, etc), but the fact is that using a non-realtime OS you don't have any guarantees about allocated timeslices, time that it takes to complete certain operations, etc.

Cd-MaN