2

I understand blocking code is a sin when it comes to event loops (i.e. NodeJS), but what about with greenlets (which I believe are green threads)? Is there an issue running code that calls blocking functions?

Matty
  • 33,203
  • 13
  • 65
  • 93

2 Answers2

7

Greenlets themselves without an event loop as provided by gevent are very primitive. A blocking call from within one greenlet will block all greenlets since greenlets alone have no capability to yield on IO operations, and no scheduler. Gevent's monkey-patching of socket and file IO is generally enough to enable non-blocking IO even with databases provided that the database library is written in python and uses sockets. Or alternately you can patch the library yourself.

philofinfinitejest
  • 3,987
  • 1
  • 24
  • 22
4

Calling function that blocks event loop is of course issue, because other green threads will be waiting for end of this function.
But if you use Gevent you can call blocking functions. Gevent patches common python blocking functions. Write this at the start of program and Gevent will patch all blocking functions:

from gevent import monkey
monkey.patch_all()
Stan
  • 4,169
  • 2
  • 31
  • 39
  • I was under the impression that green threads aren't the same thing as an event loop, and that calling blocking code in an event loop is a problem because it prevents all other requests from being processed. I wasn't sure whether calling blocking code when using greenlets would be an issue, such as blocking database calls. It seems that gevent monkey patches only blocking networking functions. – Matty Apr 18 '12 at 08:26
  • Database is different. 1) A request concurrent with a slow db request is usually also slow. Database throughput can soon decrease with number of connections. 2) A bad or slow network server should not block requests to other fast servers. Network paralellism usually increases throughput. – hynekcer Apr 18 '12 at 12:05