Note: recv() and Thread Behavior in Python
recv() is a low-level, protocol-independent socket function called by C extensions (e.g., psycopg2) to receive data from a TCP socket, like a DB response.
Python thread runs a DB call -> C extension releases GIL -> calls recv(), which blocks and thread stays blocked in the OS wait queue during recv().
Network data arrives -> NIC interrupts (per packet or batch) -> OS network stack processes TCP headers, moves payload to socket buffer, updates socket state based on TCP state for instance FIN/RST. OS wakes threads that are waiting on that socket, moving them to the run queue.
When thread run again -> C extension reacquires GIL -> recv() checks buffer and state, deciding to return or wait again.
recv() Wake and Decision:
-> Checks socket buffer. If data’s there, returns it (e.g., recv(1024) returns up to 1024, but x if that's what' there).
-> If buffer’s empty, checks socket state:
-> Open (no FIN): Blocks again if data’s partial and more’s expected, or waits if nothing’s there. Never returns 0—reserved for closure.
-> Closed (FIN, buffer empty): Returns 0, “end of stream.”
-> Errored (RST): Returns -1 with errno (e.g., ECONNRESET).
-> Non-blocking mode returns -1/EAGAIN if no data; timeouts error if set.
DB libs loop recv() for protocol completeness.
Key Point: OS wakes thread on data or state change; recv() checks buffer then state, returning data/0/error or waiting based on need.