guv.event - event primitive for greenthreads

class guv.event.Event[source]

Bases: object

An abstraction where an arbitrary number of greenlets can wait for one event from another

Events are similar to a Queue that can only hold one item, but differ in two important ways:

  1. Calling send() never unschedules the current GreenThread
  2. send() can only be called once; create a new event to send again.

They are good for communicating results between greenlets, and are the basis for how GreenThread.wait() is implemented.

>>> from guv import event
>>> import guv
>>> evt = event.Event()
>>> def baz(b):
...     evt.send(b + 1)
...
>>> _ = guv.spawn_n(baz, 3)
>>> evt.wait()
4
ready() → None[source]

Return true if the wait() call will return immediately

Used to avoid waiting for things that might take a while to time out. For example, you can put a bunch of events into a list, and then visit them all repeatedly, calling ready() until one returns True, and then you can wait() on that one

send(result=None, exc=None) → None[source]

Make arrangements for the waiters to be woken with the result and then return immediately to the parent

>>> from guv import event
>>> import guv
>>> evt = event.Event()
>>> def waiter():
...     print('about to wait')
...     result = evt.wait()
...     print('waited for {0}'.format(result))
>>> _ = guv.spawn(waiter)
>>> guv.sleep(0)
about to wait
>>> evt.send('a')
>>> guv.sleep(0)
waited for a

It is an error to call send() multiple times on the same event.

>>> evt.send('whoops')
Traceback (most recent call last):
...
AssertionError: Trying to re-send() an already-triggered event.

Use reset() between send() s to reuse an event object.

send_exception(*args) → None[source]

Same as send(), but sends an exception to waiters.

The arguments to send_exception are the same as the arguments to raise. If a single exception object is passed in, it will be re-raised when wait() is called, generating a new stacktrace.

>>> from guv import event
>>> evt = event.Event()
>>> evt.send_exception(RuntimeError())
>>> evt.wait()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "guv/event.py", line 120, in wait
    current.throw(*self._exc)
RuntimeError

If it’s important to preserve the entire original stack trace, you must pass in the entire sys.exc_info() tuple.

>>> import sys
>>> evt = event.Event()
>>> try:
...     raise RuntimeError()
... except RuntimeError:
...     evt.send_exception(*sys.exc_info())
...
>>> evt.wait()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "guv/event.py", line 120, in wait
    current.throw(*self._exc)
  File "<stdin>", line 2, in <module>
RuntimeError

Note that doing so stores a traceback object directly on the Event object, which may cause reference cycles. See the sys.exc_info() documentation.

wait() → None[source]

Wait until another greenthread calls send()

Returns the value the other coroutine passed to send().

Returns immediately if the event has already occurred.

>>> from guv import event
>>> import guv
>>> evt = event.Event()
>>> def wait_on():
...    retval = evt.wait()
...    print("waited for {0}".format(retval))
>>> _ = guv.spawn(wait_on)
>>> evt.send('result')
>>> guv.sleep(0)
waited for result
>>> evt.wait()
'result'
class guv.event.TEvent[source]

Bases: object

A synchronization primitive that allows one greenlet to wake up one or more others. It has the same interface as threading.Event but works across greenlets.

An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

clear() → None[source]

Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

isSet() → None

Return true if and only if the internal flag is true.

is_set() → None[source]

Return true if and only if the internal flag is true.

Register a callback to call when the internal flag is set to true

callback will be called in the Hub, so it must not use blocking gevent API. callback will be passed one argument: this instance.

ready() → None

Return true if and only if the internal flag is true.

set() → None[source]

Set the internal flag to true. All greenlets waiting for it to become true are awakened. Greenlets that call wait() once the flag is true will not block at all.

Remove the callback set by rawlink()

wait(timeout=None) → None[source]

Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

Return the value of the internal flag (True or False).

class guv.event.AsyncResult[source]

Bases: object

A one-time event that stores a value or an exception

Like Event it wakes up all the waiters when set() or set_exception() method is called. Waiters may receive the passed value or exception by calling get() method instead of wait(). An AsyncResult instance cannot be reset.

To pass a value call set(). Calls to get() (those that currently blocking as well as those made in the future) will return the value:

>>> result = AsyncResult()
>>> result.set(100)
>>> result.get()
100

To pass an exception call set_exception(). This will cause get() to raise that exception:

>>> result = AsyncResult()
>>> result.set_exception(RuntimeError('failure'))
>>> result.get()
Traceback (most recent call last):
 ...
RuntimeError: failure

AsyncResult implements __call__() and thus can be used as link() target:

>>> import gevent
>>> result = AsyncResult()
>>> gevent.spawn(lambda : 1/0).link(result)
>>> try:
...     result.get()
... except ZeroDivisionError:
...     print 'ZeroDivisionError'
ZeroDivisionError
exception

@property

Holds the exception instance passed to set_exception() if set_exception() was called. Otherwise None.

get(block=True, timeout=None) → None[source]

Return the stored value or raise the exception.

If this instance already holds a value / an exception, return / raise it immediatelly. Otherwise, block until another greenlet calls set() or set_exception() or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

get_nowait() → None[source]

Return the value or raise the exception without blocking.

If nothing is available, raise gevent.Timeout immediatelly.

Register a callback to call when a value or an exception is set.

callback will be called in the Hub, so it must not use blocking gevent API. callback will be passed one argument: this instance.

ready() → None[source]

Return true if and only if it holds a value or an exception

set(value=None) → None[source]

Store the value. Wake up the waiters.

All greenlets blocking on get() or wait() are woken up. Sequential calls to wait() and get() will not block at all.

set_exception(exception) → None[source]

Store the exception. Wake up the waiters.

All greenlets blocking on get() or wait() are woken up. Sequential calls to wait() and get() will not block at all.

successful() → None[source]

Return true if and only if it is ready and holds a value

Remove the callback set by rawlink()

wait(timeout=None) → None[source]

Block until the instance is ready.

If this instance already holds a value / an exception, return immediatelly. Otherwise, block until another thread calls set() or set_exception() or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

Return value.