1Threading model
2===============
3
4All OpenStack services use *green thread* model of threading, implemented
5through using the Python `eventlet <http://eventlet.net/>`_ and
6`greenlet <http://packages.python.org/greenlet/>`_ libraries.
7
8Green threads use a cooperative model of threading: thread context
9switches can only occur when specific eventlet or greenlet library calls are
10made (e.g., sleep, certain I/O calls). From the operating system's point of
11view, each OpenStack service runs in a single thread.
12
13The use of green threads reduces the likelihood of race conditions, but does
14not completely eliminate them. In some cases, you may need to use the
15``@utils.synchronized(...)`` decorator to avoid races.
16
17In addition, since there is only one operating system thread, a call that
18blocks that main thread will block the entire process.
19
20Yielding the thread in long-running tasks
21-----------------------------------------
22If a code path takes a long time to execute and does not contain any methods
23that trigger an eventlet context switch, the long-running thread will block
24any pending threads.
25
26This scenario can be avoided by adding calls to the eventlet sleep method
27in the long-running code path. The sleep call will trigger a context switch
28if there are pending threads, and using an argument of 0 will avoid introducing
29delays in the case that there is only a single green thread::
30
31    from eventlet import greenthread
32    ...
33    greenthread.sleep(0)
34
35In current code, time.sleep(0)does the same thing as greenthread.sleep(0) if
36time module is patched through eventlet.monkey_patch(). To be explicit, we recommend
37contributors use ``greenthread.sleep()`` instead of ``time.sleep()``.
38
39MySQL access and eventlet
40-------------------------
41There are some MySQL DB API drivers for oslo.db, like `PyMySQL`_, MySQL-python
42etc. PyMySQL is the default MySQL DB API driver for oslo.db, and it works well with
43eventlet. MySQL-python uses an external C library for accessing the MySQL database.
44Since eventlet cannot use monkey-patching to intercept blocking calls in a C library,
45queries to the MySQL database using libraries like MySQL-python will block the main
46thread of a service.
47
48The Diablo release contained a thread-pooling implementation that did not
49block, but this implementation resulted in a `bug`_ and was removed.
50
51See this `mailing list thread`_ for a discussion of this issue, including
52a discussion of the `impact on performance`_.
53
54.. _bug: https://bugs.launchpad.net/cinder/+bug/838581
55.. _mailing list thread: https://lists.launchpad.net/openstack/msg08118.html
56.. _impact on performance: https://lists.launchpad.net/openstack/msg08217.html
57.. _PyMySQL: https://wiki.openstack.org/wiki/PyMySQL_evaluation
58