1. Coroutines¶
The central concept of Shrapnel is the coroutine. You can think of a coroutine like it is a thread. When it runs out of work to do, it yields and allows other coroutines to run. Scheduling of coroutines is handled by the scheduler which runs an “event loop”.
1.1. Event Loop¶
The event loop is a loop that runs forever until the program ends. Every Shrapnel program needs to start the event loop as one of the first things it does. A typical example would be:
import coro
def main():
print 'Hello world!'
# This will cause the process to exit.
coro.set_exit(0)
if __name__ == '__main__':
coro.spawn(main)
coro.event_loop()
1.2. Coroutines¶
Every coroutine thread is created with either the new() function (which
does NOT automatically start the thread) or the spawn() function (which
DOES automatically start it).
Every thread has a unique numeric ID. You may also set the name of the thread when you create it.
1.3. Timeouts¶
The shrapnel timeout facility allows you to execute a function which will be
interrupted if it does not finish within a specified period of time. The
TimeoutError exception will be raised if the timeout expires. See the
with_timeout() docstring for more detail.
If the event loop is not running (such as in a non-coro process), a custom version of with_timeout is installed that will operate using SIGALRM so that you may use with_timeout in code that needs to run in non-coro processes (though this is not recommended and should be avoided if possible).
1.4. Parallel Execution¶
XXX
1.5. Thread Local Storage¶
There is a thread-local storage interface available for storing global data that
is thread-specific. You instantiate a ThreadLocal instance and you can
assign attributes to it that will be specific to that thread. From a design
perspective, it is generally discouraged to use thread-local storage. But
nonetheless, it can be useful at times.
1.6. Functions¶
The coro module defines the following functions:
1.7. Variables¶
-
coro.all_threads¶ A dictionary of all live coroutine objects. The key is the coroutine ID, and the value is the coroutine object.
1.8. Exceptions¶
The coro module defines the following exceptions: