back to Index
2014-07-19
gevent coroutines test
In [1]:
import gevent
import sys
import time
In [2]:
msgs=[]
In [ ]:
def time_test(msgs):
last_time=time.time()
i=0
while True:
now=time.time()
topush=i, (now-last_time)
i+=1
msgs.append(topush)
print(topush)
sys.stdout.flush()
last_time=now
gevent.sleep(1)
In [ ]:
In [6]:
gevent.joinall([gevent.spawn(time_test, msgs)])
In [4]:
t1=gevent.spawn(time_test)
t1.start()
In [13]:
t1.start()
In [12]:
t1.join()
In [43]:
thread.start()
In [44]:
thread.kill()
In [47]:
thread.link?
In [49]:
thread.value
In [ ]:
thread.
In [46]:
thread.join?
In [40]:
thread.started
Out[40]:
In [42]:
thread.dead
Out[42]:
In [34]:
thread.loop?
In [38]:
thread.run()
In [50]:
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo again')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit context switch back to bar')
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
In [60]:
import gevent
from gevent.queue import Queue
class Actor(gevent.Greenlet):
def __init__(self):
self.inbox = Queue()
Greenlet.__init__(self)
def receive(self, message):
"""
Define in your subclass.
"""
raise NotImplemented()
def _run(self):
self.running = True
while self.running:
message = self.inbox.get()
self.receive(message)
In [ ]:
import gevent
from gevent.queue import Queue
from gevent import Greenlet
class Pinger(Actor):
def receive(self, message):
print(message)
pong.inbox.put('ping')
gevent.sleep(0)
class Ponger(Actor):
def receive(self, message):
print(message)
ping.inbox.put('pong')
gevent.sleep(0)
ping = Pinger()
pong = Ponger()
ping.start()
pong.start()
ping.inbox.put('start')
gevent.joinall([ping, pong])
conclusions: gevent threads can't be forked.
In [ ]: