import gevent.monkeygevent.monkey.patch_all()import geventimport gevent.hubimport time
hub = gevent.hub.get_hub()loop = hub.loop
def worker(worker_id):for iteration in xrange(3):print 'worker: %d, pendingcnt: %d, activecnt: %d' % (worker_id, loop.pendingcnt, loop.activecnt)# Simulate making a yielding call to some API. The call takes 3 seconds.time.sleep(3)# Spawn 5 greenlets in a staggered fashion, kicking them of 0.5 seconds# apart. This ensure that each greenlet will make its fake API call at# a different time, which means that the API call will also finish at# a different time. Bottom line: each greenlet will want to run at a# different time (no waiting).greenlets = []for worker_id in xrange(5):greenlet = gevent.spawn(worker, worker_id)greenlets.append(greenlet)time.sleep(.5)gevent.joinall(greenlets)print 'done'
(venv)~/work> python g1.py
worker: 0, pendingcnt: 0, activecnt: 1
worker: 1, pendingcnt: 0, activecnt: 2
worker: 2, pendingcnt: 0, activecnt: 3
worker: 3, pendingcnt: 0, activecnt: 4
worker: 4, pendingcnt: 0, activecnt: 5
worker: 0, pendingcnt: 0, activecnt: 4
worker: 1, pendingcnt: 0, activecnt: 4
worker: 2, pendingcnt: 0, activecnt: 4
worker: 3, pendingcnt: 0, activecnt: 4
worker: 4, pendingcnt: 0, activecnt: 4
worker: 0, pendingcnt: 0, activecnt: 4
worker: 1, pendingcnt: 0, activecnt: 4
worker: 2, pendingcnt: 0, activecnt: 4
worker: 3, pendingcnt: 0, activecnt: 4
worker: 4, pendingcnt: 0, activecnt: 4
done
import gevent.monkeygevent.monkey.patch_all()import geventimport gevent.hubimport time
hub = gevent.hub.get_hub()loop = hub.loop
def worker(worker_id):# First yield so we'll get a chance to spawn all the greenlets.time.sleep(0.001)for iteration in xrange(3):print 'worker: %d, pendingcnt: %d, activecnt: %d' % (worker_id, loop.pendingcnt, loop.activecnt)# Simulate actively using the CPU for 0.5 seconds.start_time = time.time()target_time = start_time + 0.5while time.time() < target_time:pass# Now yield so others can run.time.sleep(0.001)# Kick off all the greenlets at once. Each one will perform busy work# so we should expect to see some contention for CPU.greenlets = [gevent.spawn(worker, worker_id) for worker_id in xrange(5)]gevent.joinall(greenlets)print 'done'
(venv)~/work> python g2.py
worker: 0, pendingcnt: 4, activecnt: 0
worker: 1, pendingcnt: 3, activecnt: 1
worker: 2, pendingcnt: 2, activecnt: 2
worker: 3, pendingcnt: 1, activecnt: 3
worker: 4, pendingcnt: 0, activecnt: 4
worker: 0, pendingcnt: 3, activecnt: 1
worker: 1, pendingcnt: 2, activecnt: 2
worker: 2, pendingcnt: 1, activecnt: 3
worker: 3, pendingcnt: 0, activecnt: 4
worker: 4, pendingcnt: 3, activecnt: 1
worker: 0, pendingcnt: 2, activecnt: 2
worker: 1, pendingcnt: 1, activecnt: 3
worker: 2, pendingcnt: 0, activecnt: 4
worker: 3, pendingcnt: 3, activecnt: 1
worker: 4, pendingcnt: 2, activecnt: 2
done