amazingjxq
amazingjxq

Reputation: 4677

How could gevent socket block only the current greenlet?

I'm reading gevent.socket but I don't understand.

def recv(self, *args):
    sock = self._sock  # keeping the reference so that fd is not closed during waiting
    while True:
        try:
            return sock.recv(*args)
        except error, ex:
            if ex[0] == EBADF:
                return ''
            if ex[0] != EWOULDBLOCK or self.timeout == 0.0:
                raise
            # QQQ without clearing exc_info test__refcount.test_clean_exit fails
            sys.exc_clear()
        try:
            wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
        except error, ex:
            if ex[0] == EBADF:
                return ''
            raise

The sock in recv is an instance of _realsocket(family, type, proto). And in socket.py I found:

import _socket
_realsocket = _socket.socket

What is _socket? Why wouldn't return sock.recv(*args) block the whole program?

Upvotes: 1

Views: 559

Answers (1)

kimjxie
kimjxie

Reputation: 801

The _socket is a standard c library of python which provides the real network communication, and socket.py (in standard library or gevent) wrap methods up for common using.

Then, look into init of class Socket in gevent.socket,

```self._sock.setblocking(0)```

this statement make the socket object nonblocking

Upvotes: 1

Related Questions