Skip to contentSkip to conversation

Coroutines for better asynchronous programming

PATCH In review Stefan Hajnoczi 2 participants 8 messages Jun 27, 2011 – Jul 18, 2011 Kbuild

lore
Share & tools
lore
#0 lore raw

v6 cover Coroutines for better asynchronous programming

Here is the latest version of the coroutine series with Mac OS X fixes from Andreas Färber <[email protected]>.

QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes. Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed. This allows QEMU to continue executing while the operation is pending.

The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand. Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.

This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow. The semantics are explained in the second patch. The fourth patch adds automated tests.

A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous. Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses). This qcow2 work is still ongoing and not quite ready for mainline yet.

Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.

v6:
* Use GThread on Mac OS X, fix from Andreas Färber <[email protected]>
* abort(3) if coroutine-ucontext.c fails to create a coroutine

v5:
* GThread-based implementation for platforms without makecontext(3) (Aneesh Kumar K.V <[email protected]>)
* Switch to gtester test framework

v4:
* Windows Fibers support (Paolo Bonzini <[email protected]>)
* Return-after-setjmp() fix (Aneesh Kumar K.V <[email protected]>)
* Re-entrancy for multi-threaded coroutines support
* qemu-coroutine.h cleanup and documentation

v3:
* Updated LGPL v2 license header to use web link
* Removed atexit(3) pool freeing
* Removed thread-local current/leader
* Documented thread-safety limitation
* Disabled trace events

v2:
* Added ./check-coroutine --lifecycle-benchmark for performance measurement
* Split pooling into a separate patch with performance justification
* Set maximum pool size to prevent holding onto too many free coroutines
* Added atexit(3) handler to free pool
* Coding style cleanups

Aneesh Kumar K.V (1):
coroutine: implement coroutines using gthread

Anthony Liguori (1):
Add hard build dependency on glib

Kevin Wolf (1):
coroutine: introduce coroutines

Stefan Hajnoczi (2):
coroutine: add test-coroutine automated tests
coroutine: add test-coroutine --benchmark-lifecycle

 .gitignore           |    1 +
 Makefile             |    5 +-
 Makefile.objs        |   13 +++
 Makefile.target      |    1 +
 configure            |   31 +++++++
 coroutine-gthread.c  |  131 ++++++++++++++++++++++++++++
 coroutine-ucontext.c |  230 ++++++++++++++++++++++++++++++++++++++++++++++++++
 coroutine-win32.c    |   92 ++++++++++++++++++++
 qemu-coroutine-int.h |   48 +++++++++++
 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 test-coroutine.c     |  192 +++++++++++++++++++++++++++++++++++++++++
 trace-events         |    5 +
 13 files changed, 918 insertions(+), 1 deletions(-)
 create mode 100644 coroutine-gthread.c
 create mode 100644 coroutine-ucontext.c
 create mode 100644 coroutine-win32.c
 create mode 100644 qemu-coroutine-int.h
 create mode 100644 qemu-coroutine.c
 create mode 100644 qemu-coroutine.h
 create mode 100644 test-coroutine.c
Signature · 1 line
1.7.5.4
#1 lore raw

PATCH v6 1/5 Add hard build dependency on glib

From: Anthony Liguori <[email protected]>

GLib is an extremely common library that has a portable thread implementation along with tons of other goodies.

GLib and GObject have a fantastic amount of infrastructure we can leverage in QEMU including an object oriented programming infrastructure.

Short term, it has a very nice thread pool implementation that we could leverage in something like virtio-9p. It also has a test harness implementation that this series will use.

---
 Makefile        |    2 ++
 Makefile.objs   |    2 ++
 Makefile.target |    1 +
 configure       |   13 +++++++++++++
 4 files changed, 18 insertions(+), 0 deletions(-)
Makefile +2 -0
index b3ffbe2..42ae4e5 100644
@@ -106,6 +106,8 @@ audio/audio.o audio/fmodaudio.o: QEMU_CFLAGS += $(FMOD_CFLAGS)
 
 QEMU_CFLAGS+=$(CURL_CFLAGS)
 
+QEMU_CFLAGS+=$(GLIB_CFLAGS)
+
 ui/cocoa.o: ui/cocoa.m
 
 ui/sdl.o audio/sdlaudio.o ui/sdl_zoom.o baum.o: QEMU_CFLAGS += $(SDL_CFLAGS)
Makefile.objs +2 -0
index cea15e4..493c988 100644
@@ -376,3 +376,5 @@ vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
 
+vl.o: QEMU_CFLAGS+=$(GLIB_CFLAGS)
+
Makefile.target +1 -0
index 38afdb8..05bd61d 100644
@@ -203,6 +203,7 @@ QEMU_CFLAGS += $(VNC_TLS_CFLAGS)
 QEMU_CFLAGS += $(VNC_SASL_CFLAGS)
 QEMU_CFLAGS += $(VNC_JPEG_CFLAGS)
 QEMU_CFLAGS += $(VNC_PNG_CFLAGS)
+QEMU_CFLAGS += $(GLIB_CFLAGS)
 
 # xen backend driver support
 obj-i386-$(CONFIG_XEN) += xen_machine_pv.o xen_domainbuild.o
configure +13 -0
index e523976..c7661bc 100755
@@ -1803,6 +1803,18 @@ EOF
 fi
 
 ##########################################
+# glib support probe
+if $pkg_config --modversion gthread-2.0 gio-2.0 > /dev/null 2>&1 ; then
+    glib_cflags=`$pkg_config --cflags gthread-2.0 gio-2.0 2>/dev/null`
+    glib_libs=`$pkg_config --libs gthread-2.0 gio-2.0 2>/dev/null`
+    libs_softmmu="$glib_libs $libs_softmmu"
+    libs_tools="$glib_libs $libs_tools"
+else
+    echo "glib-2.0 required to compile QEMU"
+    exit 1
+fi
+
+##########################################
 # pthread probe
 PTHREADLIBS_LIST="-lpthread -lpthreadGC2"
 
@@ -2849,6 +2861,7 @@ if test "$bluez" = "yes" ; then
   echo "CONFIG_BLUEZ=y" >> $config_host_mak
   echo "BLUEZ_CFLAGS=$bluez_cflags" >> $config_host_mak
 fi
+echo "GLIB_CFLAGS=$glib_cflags" >> $config_host_mak
 if test "$xen" = "yes" ; then
   echo "CONFIG_XEN=y" >> $config_host_mak
   echo "CONFIG_XEN_CTRL_INTERFACE_VERSION=$xen_ctrl_version" >> $config_host_mak
Signature · 1 line
1.7.5.4
#2 lore raw

PATCH v6 2/5 coroutine: introduce coroutines

In reply to Stefan Hajnoczi

From: Kevin Wolf <[email protected]>

Asynchronous code is becoming very complex. At the same time synchronous code is growing because it is convenient to write. Sometimes duplicate code paths are even added, one synchronous and the other asynchronous. This patch introduces coroutines which allow code that looks synchronous but is asynchronous under the covers.

A coroutine has its own stack and is therefore able to preserve state across blocking operations, which traditionally require callback functions and manual marshalling of parameters.

Creating and starting a coroutine is easy:

  coroutine = qemu_coroutine_create(my_coroutine);
  qemu_coroutine_enter(coroutine, my_data);

The coroutine then executes until it returns or yields:

  void coroutine_fn my_coroutine(void *opaque) {
      MyData *my_data = opaque;
      /* do some work */

      qemu_coroutine_yield();

      /* do some more work */

}

Yielding switches control back to the caller of qemu_coroutine_enter(). This is typically used to switch back to the main thread's event loop after issuing an asynchronous I/O request. The request callback will then invoke qemu_coroutine_enter() once more to switch back to the coroutine.

Note that if coroutines are used only from threads which hold the global mutex they will never execute concurrently. This makes programming with coroutines easier than with threads. Race conditions cannot occur since only one coroutine may be active at any time. Other coroutines can only run across yield.

This coroutines implementation is based on the gtk-vnc implementation written by Anthony Liguori <[email protected]> but it has been significantly rewritten by Kevin Wolf <[email protected]> to use setjmp()/longjmp() instead of the more expensive swapcontext() and by Paolo Bonzini <[email protected]> for Windows Fibers support.

---
 Makefile.objs        |    7 ++
 coroutine-ucontext.c |  230 ++++++++++++++++++++++++++++++++++++++++++++++++++
 coroutine-win32.c    |   92 ++++++++++++++++++++
 qemu-coroutine-int.h |   48 +++++++++++
 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 trace-events         |    5 +
 7 files changed, 552 insertions(+), 0 deletions(-)
 create mode 100644 coroutine-ucontext.c
 create mode 100644 coroutine-win32.c
 create mode 100644 qemu-coroutine-int.h
 create mode 100644 qemu-coroutine.c
 create mode 100644 qemu-coroutine.h
Makefile.objs +7 -0
index 493c988..e24bcd7 100644
@@ -11,6 +11,12 @@ oslib-obj-$(CONFIG_WIN32) += oslib-win32.o qemu-thread-win32.o
 oslib-obj-$(CONFIG_POSIX) += oslib-posix.o qemu-thread-posix.o
 
 #######################################################################
+# coroutines
+coroutine-obj-y = qemu-coroutine.o
+coroutine-obj-$(CONFIG_POSIX) += coroutine-ucontext.o
+coroutine-obj-$(CONFIG_WIN32) += coroutine-win32.o
+
+#######################################################################
 # block-obj-y is code used by both qemu system emulation and qemu-img
 
 block-obj-y = cutils.o cache-utils.o qemu-malloc.o qemu-option.o module.o async.o
@@ -69,6 +75,7 @@ common-obj-y += readline.o console.o cursor.o qemu-error.o
 common-obj-y += $(oslib-obj-y)
 common-obj-$(CONFIG_WIN32) += os-win32.o
 common-obj-$(CONFIG_POSIX) += os-posix.o
+common-obj-y += $(coroutine-obj-y)
 
 common-obj-y += tcg-runtime.o host-utils.o
 common-obj-y += irq.o ioport.o input.o
coroutine-ucontext.c new file +230 -0

230 lines not on this page · raw message

coroutine-win32.c new file +92 -0

92 lines not on this page · raw message

qemu-coroutine-int.h new file +48 -0

48 lines not on this page · raw message

qemu-coroutine.c new file +75 -0

75 lines not on this page · raw message

qemu-coroutine.h new file +95 -0

95 lines not on this page · raw message

trace-events +5 -0
index bebf612..ebe4df9 100644
@@ -410,3 +410,8 @@ disable qemu_put_ram_ptr(void* addr) "%p"
 
 # hw/xen_platform.c
 disable xen_platform_log(char *s) "xen platform: %s"
+
+# qemu-coroutine.c
+disable qemu_coroutine_enter(void *from, void *to, void *opaque) "from %p to %p opaque %p"
+disable qemu_coroutine_yield(void *from, void *to) "from %p to %p"
+disable qemu_coroutine_terminate(void *co) "self %p"
Signature · 1 line
1.7.5.4
#3 lore raw

PATCH v6 3/5 coroutine: implement coroutines using gthread

In reply to Stefan Hajnoczi

From: "Aneesh Kumar K.V" <[email protected]>

On platforms that don't support makecontext(3) use gthread based coroutine implementation.

Darwin has makecontext(3) but getcontext(3) is stubbed out to return ENOTSUP. Andreas Färber <[email protected]> debugged this and contributed the ./configure test which solves the issue for Darwin/ppc64 (and ppc) v10.5.

[Original patch by Aneesh, made consistent with coroutine-ucontext.c and switched to GStaticPrivate by Stefan. Tested on Linux and OpenBSD.]

---
 Makefile.objs       |    4 ++
 configure           |   18 +++++++
 coroutine-gthread.c |  131 +++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 153 insertions(+), 0 deletions(-)
 create mode 100644 coroutine-gthread.c
Makefile.objs +4 -0
index e24bcd7..d9ade62 100644
@@ -13,7 +13,11 @@ oslib-obj-$(CONFIG_POSIX) += oslib-posix.o qemu-thread-posix.o
 #######################################################################
 # coroutines
 coroutine-obj-y = qemu-coroutine.o
+ifeq ($(CONFIG_UCONTEXT_COROUTINE),y)
 coroutine-obj-$(CONFIG_POSIX) += coroutine-ucontext.o
+else
+coroutine-obj-$(CONFIG_POSIX) += coroutine-gthread.o
+endif
 coroutine-obj-$(CONFIG_WIN32) += coroutine-win32.o
 
 #######################################################################
configure +18 -0
index c7661bc..20ba068 100755
@@ -2476,6 +2476,20 @@ if test "$trace_backend" = "dtrace"; then
 fi
 
 ##########################################
+# check if we have makecontext
+
+ucontext_coroutine=no
+if test "$darwin" != "yes"; then
+  cat > $TMPC << EOF
+#include <ucontext.h>
+int main(void) { makecontext(0, 0, 0); }
+EOF
+  if compile_prog "" "" ; then
+      ucontext_coroutine=yes
+  fi
+fi
+
+##########################################
 # End of CC checks
 # After here, no more $cc or $ld runs
 
@@ -2941,6 +2955,10 @@ if test "$rbd" = "yes" ; then
   echo "CONFIG_RBD=y" >> $config_host_mak
 fi
 
+if test "$ucontext_coroutine" = "yes" ; then
+  echo "CONFIG_UCONTEXT_COROUTINE=y" >> $config_host_mak
+fi
+
 # USB host support
 case "$usb" in
 linux)
coroutine-gthread.c new file +131 -0

131 lines not on this page · raw message

Signature · 1 line
1.7.5.4
#4 lore raw

PATCH v6 4/5 coroutine: add test-coroutine automated tests

In reply to Stefan Hajnoczi

To run automated tests for coroutines:

make test-coroutine
./test-coroutine

On success the program terminates with exit status 0. On failure an error message is written to stderr and the program exits with exit status 1.

---
 .gitignore       |    1 +
 Makefile         |    3 +-
 test-coroutine.c |  162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 165 insertions(+), 1 deletions(-)
 create mode 100644 test-coroutine.c
.gitignore +1 -0
index 08013fc..3ad334a 100644
@@ -34,6 +34,7 @@ qemu-img-cmds.h
 qemu-io
 qemu-monitor.texi
 QMP/qmp-commands.txt
+test-coroutine
 .gdbinit
 *.a
 *.aux
Makefile +2 -1
index 42ae4e5..98986ad 100644
@@ -151,7 +151,7 @@ qemu-io$(EXESUF): qemu-io.o cmd.o qemu-tool.o qemu-error.o $(oslib-obj-y) $(trac
 qemu-img-cmds.h: $(SRC_PATH)/qemu-img-cmds.hx
 	$(call quiet-command,sh $(SRC_PATH)/scripts/hxtool -h < $< > $@,"  GEN   $@")
 
-check-qint.o check-qstring.o check-qdict.o check-qlist.o check-qfloat.o check-qjson.o: $(GENERATED_HEADERS)
+check-qint.o check-qstring.o check-qdict.o check-qlist.o check-qfloat.o check-qjson.o test-coroutine.o: $(GENERATED_HEADERS)
 
 CHECK_PROG_DEPS = qemu-malloc.o $(oslib-obj-y) $(trace-obj-y) qemu-tool.o
 
@@ -161,6 +161,7 @@ check-qdict: check-qdict.o qdict.o qfloat.o qint.o qstring.o qbool.o qlist.o $(C
 check-qlist: check-qlist.o qlist.o qint.o $(CHECK_PROG_DEPS)
 check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS)
 check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o error.o qerror.o qemu-error.o $(CHECK_PROG_DEPS)
+test-coroutine: test-coroutine.o $(coroutine-obj-y) $(CHECK_PROG_DEPS)
 
 QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
 
test-coroutine.c new file +162 -0

162 lines not on this page · raw message

Signature · 1 line
1.7.5.4
#5 lore raw

PATCH v6 5/5 coroutine: add test-coroutine --benchmark-lifecycle

In reply to Stefan Hajnoczi

Add a microbenchmark for coroutine create, enter, and return (aka lifecycle). This is a useful benchmark because users are expected to create many coroutines, one per I/O request for example, and we therefore need to provide good performance in that scenario.

To run:

  make test-coroutine
  ./test-coroutine --benchmark-lifecycle 20000000

This will do 20,000,000 coroutine create, enter, return iterations and print the resulting time.

---
 test-coroutine.c |   30 ++++++++++++++++++++++++++++++
 1 files changed, 30 insertions(+), 0 deletions(-)
test-coroutine.c +30 -0
index 9e9d3c9..bf9f3e9 100644
@@ -150,6 +150,33 @@ static void test_lifecycle(void)
     g_assert(done); /* expect done to be true (second time) */
 }
 
+/*
+ * Lifecycle benchmark
+ */
+
+static void coroutine_fn empty_coroutine(void *opaque)
+{
+    /* Do nothing */
+}
+
+static void perf_lifecycle(void)
+{
+    Coroutine *coroutine;
+    unsigned int i, max;
+    double duration;
+
+    max = 1000000;
+
+    g_test_timer_start();
+    for (i = 0; i < max; i++) {
+        coroutine = qemu_coroutine_create(empty_coroutine);
+        qemu_coroutine_enter(coroutine, NULL);
+    }
+    duration = g_test_timer_elapsed();
+
+    g_test_message("Lifecycle %u iterations: %f s\n", max, duration);
+}
+
 int main(int argc, char **argv)
 {
     g_test_init(&argc, &argv, NULL);
@@ -158,5 +185,8 @@ int main(int argc, char **argv)
     g_test_add_func("/basic/nesting", test_nesting);
     g_test_add_func("/basic/self", test_self);
     g_test_add_func("/basic/in_coroutine", test_in_coroutine);
+    if (g_test_perf()) {
+        g_test_add_func("/perf/lifecycle", perf_lifecycle);
+    }
     return g_test_run();
 }
Signature · 1 line
1.7.5.4
#6 lore raw
In reply to Stefan Hajnoczi
Quoted 19 lines · Stefan Hajnoczi

Here is the latest version of the coroutine series with Mac OS X fixes from Andreas Färber <[email protected]>.

QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes.  Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed.  This allows QEMU to continue executing while the operation is pending.

The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand.  Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.

This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow.  The semantics are explained in the second patch.  The fourth patch adds automated tests.

Quoted 8 lines

A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous.  Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses).  This qcow2 work is still ongoing and not quite ready for mainline yet.

Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.

Coroutines seem to work fine on OpenBSD (Sparc64, also tests are passed) and mingw32, with a few minor issues.

With simpletrace enabled there is a link failure:

$ make test-coroutine
  LINK  test-coroutine
simpletrace.o: In function `get_clock':
/src/qemu/qemu-timer.h:117: undefined reference to `use_rt_clock'

This can be fixed for example by adding qemu-timer-common.o to the list of linked objects.

I can't compile coroutine tests for Mingw32 because of this:

$ make test-coroutine
  CC    test-coroutine.o
In file included from
/usr/local/i686-mingw32msvc/include/glib-2.0/glib/galloca.h:30:0,
                 from /usr/local/i686-mingw32msvc/include/glib-2.0/glib.h:30,
                 from /src/qemu/test-coroutine.c:14:
/usr/local/i686-mingw32msvc/include/glib-2.0/glib/gtypes.h:30:24:
fatal error: glibconfig.h: No such file or directory

I used glib win32 zips from
http://ftp.gnome.org/pub/gnome/binaries/win32/glib/2.12/, is there a better site? Otherwise QEMU builds fine and runs under Wine nicely.

Quoted 68 lines

v6:
 * Use GThread on Mac OS X, fix from Andreas Färber <[email protected]>
 * abort(3) if coroutine-ucontext.c fails to create a coroutine

v5:
 * GThread-based implementation for platforms without makecontext(3) (Aneesh Kumar K.V <[email protected]>)
 * Switch to gtester test framework

v4:
 * Windows Fibers support (Paolo Bonzini <[email protected]>)
 * Return-after-setjmp() fix (Aneesh Kumar K.V <[email protected]>)
 * Re-entrancy for multi-threaded coroutines support
 * qemu-coroutine.h cleanup and documentation

v3:
 * Updated LGPL v2 license header to use web link
 * Removed atexit(3) pool freeing
 * Removed thread-local current/leader
 * Documented thread-safety limitation
 * Disabled trace events

v2:
 * Added ./check-coroutine --lifecycle-benchmark for performance measurement
 * Split pooling into a separate patch with performance justification
 * Set maximum pool size to prevent holding onto too many free coroutines
 * Added atexit(3) handler to free pool
 * Coding style cleanups

Aneesh Kumar K.V (1):
 coroutine: implement coroutines using gthread

Anthony Liguori (1):
 Add hard build dependency on glib

Kevin Wolf (1):
 coroutine: introduce coroutines

Stefan Hajnoczi (2):
 coroutine: add test-coroutine automated tests
 coroutine: add test-coroutine --benchmark-lifecycle

 .gitignore           |    1 +
 Makefile             |    5 +-
 Makefile.objs        |   13 +++
 Makefile.target      |    1 +
 configure            |   31 +++++++
 coroutine-gthread.c  |  131 ++++++++++++++++++++++++++++ coroutine-ucontext.c |  230 ++++++++++++++++++++++++++++++++++++++++++++++++++ coroutine-win32.c    |   92 ++++++++++++++++++++ qemu-coroutine-int.h |   48 +++++++++++

 qemu-coroutine.c     |   75 ++++++++++++++++
 qemu-coroutine.h     |   95 +++++++++++++++++++++
 test-coroutine.c     |  192 +++++++++++++++++++++++++++++++++++++++++
 trace-events         |    5 +
 13 files changed, 918 insertions(+), 1 deletions(-)

 create mode 100644 coroutine-gthread.c
 create mode 100644 coroutine-ucontext.c
 create mode 100644 coroutine-win32.c
 create mode 100644 qemu-coroutine-int.h
 create mode 100644 qemu-coroutine.c
 create mode 100644 qemu-coroutine.h
 create mode 100644 test-coroutine.c

--
1.7.5.4

#7 lore raw
Quoted 32 lines · Blue Swirl
Quoted 19 lines · Stefan Hajnoczi

Here is the latest version of the coroutine series with Mac OS X fixes from Andreas Färber <[email protected]>.

QEMU is event-driven and suffers when blocking operations are performed because VM execution may be stopped until the operation completes.  Therefore many operations that could block are performed asynchronously and a callback is invoked when the operation has completed.  This allows QEMU to continue executing while the operation is pending.

The downside to callbacks is that they split up code into many smaller functions, each of which is a single step in a state machine that quickly becomes complex and hard to understand.  Callback functions also result in lots of noise as variables are packed and unpacked into temporary structs that pass state to the callback function.

This patch series introduces coroutines as a solution for writing asynchronous code while still having a nice sequential control flow.  The semantics are explained in the second patch.  The fourth patch adds automated tests.

Quoted 8 lines

A nice feature of coroutines is that it is relatively easy to take synchronous code and lift it into a coroutine to make it asynchronous.  Work has been done to move qcow2 request processing into coroutines and thereby make it asynchronous (today qcow2 will perform synchronous metadata accesses).  This qcow2 work is still ongoing and not quite ready for mainline yet.

Coroutines are also being used for virtfs (virtio-9p) so I have submitted this patch now because virtfs patches that depend on coroutines are being published.

Coroutines seem to work fine on OpenBSD (Sparc64, also tests are passed) and mingw32, with a few minor issues.

Quoted 8 lines

With simpletrace enabled there is a link failure:

$ make test-coroutine
 LINK  test-coroutine
simpletrace.o: In function `get_clock':
/src/qemu/qemu-timer.h:117: undefined reference to `use_rt_clock'

This can be fixed for example by adding qemu-timer-common.o to the list of linked objects.

Do you want me to send a patch to add qemu-timer-common.o or is this easy to do while merging?

Quoted 10 lines

I can't compile coroutine tests for Mingw32 because of this:

$ make test-coroutine
 CC    test-coroutine.o
In file included from
/usr/local/i686-mingw32msvc/include/glib-2.0/glib/galloca.h:30:0,
                from /usr/local/i686-mingw32msvc/include/glib-2.0/glib.h:30,
                from /src/qemu/test-coroutine.c:14:
/usr/local/i686-mingw32msvc/include/glib-2.0/glib/gtypes.h:30:24:
fatal error: glibconfig.h: No such file or directory
Quoted 3 lines

I used glib win32 zips from
http://ftp.gnome.org/pub/gnome/binaries/win32/glib/2.12/, is there a better site? Otherwise QEMU builds fine and runs under Wine nicely.

Paolo, Stefan Weil: Any ideas regarding w32 glib headers above?

Stefan