back to Index

gevent_longrunning_test

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)])


(0, 1.9073486328125e-06)
(5, 2.273576021194458)
(1, 1.0015571117401123)
(6, 1.0071189403533936)
(2, 1.0073168277740479)
(7, 1.0073130130767822)
(3, 1.0069432258605957)
(8, 1.0073120594024658)
KeyboardInterrupt
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-6-1dbbb66f39c6> in <module>()
----> 1 gevent.joinall([gevent.spawn(time_test, msgs)])

/usr/local/lib/python2.7/dist-packages/gevent/greenlet.pyc in joinall(greenlets, timeout, raise_error, count)
    398 def joinall(greenlets, timeout=None, raise_error=False, count=None):
    399     if not raise_error:
--> 400         wait(greenlets, timeout=timeout)
    401     else:
    402         for obj in iwait(greenlets, timeout=timeout):

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in wait(objects, timeout, count)
    643     result = []
    644     if count is None:
--> 645         return list(iwait(objects, timeout))
    646     for obj in iwait(objects=objects, timeout=timeout):
    647         result.append(obj)

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in iwait(objects, timeout)
    596             obj.rawlink(switch)
    597         for _ in xrange(count):
--> 598             item = waiter.get()
    599             waiter.clear()
    600             if item is _NONE:

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in get(self)
    566             self.greenlet = getcurrent()
    567             try:
--> 568                 return self.hub.switch()
    569             finally:
    570                 self.greenlet = None

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in switch(self)
    329         if switch_out is not None:
    330             switch_out()
--> 331         return greenlet.switch(self)
    332 
    333     def switch_out(self):

KeyboardInterrupt: 

In [4]:
t1=gevent.spawn(time_test)
t1.start()

In [13]:
t1.start()

In [12]:
t1.join()


4.94878196716
4.92703700066
1.00604891777
1.01058506966
1.00153803825
1.00190496445
KeyboardInterrupt
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-12-0a00ab691c26> in <module>()
----> 1 t1.join()

/usr/local/lib/python2.7/dist-packages/gevent/greenlet.pyc in join(self, timeout)
    288                 t = Timeout.start_new(timeout)
    289                 try:
--> 290                     result = self.parent.switch()
    291                     assert result is self, 'Invalid switch into Greenlet.join(): %r' % (result, )
    292                 finally:

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in switch(self)
    329         if switch_out is not None:
    330             switch_out()
--> 331         return greenlet.switch(self)
    332 
    333     def switch_out(self):

KeyboardInterrupt: 

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]:
False

In [42]:
thread.dead


Out[42]:
False

In [34]:
thread.loop?

In [38]:
thread.run()


2.21729278564e-05
1.01684689522
1.01220703125
1.0278429985
1.00872707367
KeyboardInterrupt
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 327, in run
    result = self._run(*self.args, **self.kwargs)
  File "<ipython-input-36-41f1618ab2b4>", line 9, in time_test
    gevent.sleep(1)
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 75, in sleep
    hub.wait(loop.timer(seconds, ref=ref))
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 341, in wait
    result = waiter.get()
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 568, in get
    return self.hub.switch()
  File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 331, in switch
    return greenlet.switch(self)
KeyboardInterrupt
<Greenlet at 0x139d620: time_test> failed with KeyboardInterrupt

---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-38-3a4699a2fe0e> in <module>()
----> 1 thread.run()

/usr/local/lib/python2.7/dist-packages/gevent/greenlet.pyc in run(self)
    327                 result = self._run(*self.args, **self.kwargs)
    328             except:
--> 329                 self._report_error(sys.exc_info())
    330                 return
    331             self._report_result(result)

/usr/local/lib/python2.7/dist-packages/gevent/greenlet.pyc in _report_error(self, exc_info)
    316             self._notifier = self.parent.loop.run_callback(self._notify_links)
    317 
--> 318         self.parent.handle_error(self, *exc_info)
    319 
    320     def run(self):

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in handle_error(self, context, type, value, tb)
    293             self.print_exception(context, type, value, tb)
    294         if context is None or issubclass(type, self.SYSTEM_ERROR):
--> 295             self.handle_system_error(type, value)
    296 
    297     def handle_system_error(self, type, value):

/usr/local/lib/python2.7/dist-packages/gevent/hub.pyc in handle_system_error(self, type, value)
    298         current = getcurrent()
    299         if current is self or current is self.parent or self.loop is None:
--> 300             self.parent.throw(type, value)
    301         else:
    302             # in case system error was handled and life goes on

KeyboardInterrupt: 

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),
])


Running in foo
Explicit context to bar
Explicit context switch to foo again
Implicit context switch back to 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 [ ]: