Monday, May 25, 2015

Multithreading in Python using PyQt and Cython to wrap a C library

Welcome! I've finally decided to make a technical blog.  Here's my first post, I hope it proves useful.

Background

This post will show an example I threw together last week as a proof of concept.  Why would you want to do this?  Here's the background:
  • We're building a GUI application that needs to run a long running CPU intensive function and update the GUI while the function is executing.
  • We have a lot of C code that works just fine so no need to duplicate it in Python.  We're using Cmake to build it.  It's a powerful and complicated cross platform build tool for C/C++ (and Fortran, if you must).  I've wrapped a very small amount of C code in this demo.
  • We want to update our PyQy GUI while we're calling our C function.  This is typically done in C with callbacks.  Luckily we can support this in Python by using Cython.  In a sentence Cython lets you write Python C extensions in a Python-like language instead of using the Python C-API.  It also gives you access to a lot of the power (and risk!) of C.

Here's the approach I took to solve this problem:
  1. Build the C library using Cmake.
  2. Wrap the C code with Cython to give us access to the underlying C functions using setuptools (a replacement for distutils).  We'll be using a Cython callback that releases the global interpreter lock or GIL, more on that later.
  3. Call the Cython wrapper from a PyQt app.  We'll put this in a Qthread so the main thread and the worker thread can run at the same time.
As a demo I'll make a simple PyQt app that displays a progress bar.  The C function takes a few seconds to run, so we're using a callback to get the percentage complete and updating the progress bar with this info.

There's lots of ways to wrap a C library with Python, too many to mention so here's a link.  Another one to look at is CFFI, from the folks behind Pypy.  It can run callbacks and also releases the GIL automatically.  I've chosen Cython for a few reasons, but mainly because it integrates very well with NumPy and can let you wrap C functions very easily.  It's also very popular in the scientific community.  It lets you write pythonic Cython code than runs close to C speed without the need to write any C.  In the long term Pypy could offer a better solution to running code in parallel with Software Transactional Memory (STM), but it's still a work in progress so I'll stick to Cython for this demo.

Cython has pretty good documentation, but it can be challenging to pull it all together.  I'll share a github repo in this post, which you can clone and use as a demo.  With a few commands (and the right dependencies installed) you'll be able to run the same example on your machine.  I'm using Ubuntu 14.04, so your milage may vary - especially on Windows.  Nothing here is platform specific, but it would take a little more work to get it running natively on Windows.  From memory the Cmake build will output a .lib or .dll file instead of a .a or .so file on Windows which you'll need to link with.

One really interesting feature in Cython is the ability to use a Cython "cdef" function as a callback for a C function, as long as it accepts the same parameters the C expects.  Both C and Cython are very static, but Cython gives us the ability to call arbitrary Python code.  This means we can pass any Python function or method to our Cython C wrapper!  If this sounds complicated that's because it is.  No worries, it'll make sense in the demo.

Important note: we're wrapping a C library in this demo, but you as long as you follow the rules you can release the GIL in your Cython code.  This will let you run threads that run in parallel without the need for C or multiple processes.

Clone the repo

We'll be cloning a git repo using the following commands:
  • Install Cmake if you don't have it, eg: "sudo apt-get install cmake" on Ubuntu.  Most Linux distros have Cmake in their main repos and there are packages available for Windows and Mac.
  • clone the git repo: "git clone https://github.com/crleblanc/pyqt_cython_and_c.git"
  • You should now have a directory called pyqt_cython_and_c with files under it.

Building the C library

This isn't a blog post about C code, since I'd rather use Python!  My example is very simple, it runs a for loop which calls a C callback and does a bunch of useless number crunching to keep the CPU busy and should take a couple seconds to run.  We'll use CMake to build it.  One important thing is to include the -fPIC flag so we can link to it properly from our Cython module.

Here's a gist of the C code, but it may change in the git repo:

We're doing some very simple error checking.  We check to see that our callback returns zero, and if it doesn't we print an error to stdout, break out of the loop and exit with a non-zero status.

Cmake takes a bit of time to come to grips with, but this is a very simple demo so I've kept it as simple as possible.  The most important file is CMakeLists.txt.  This sets up the rules to build a library called "cproject" and adds the -fPIC flag to the compiler if it supports it.

Run the following commands to build the C library, installing the library objects to lib and header files to include, relative to your current working directory.
  • cd to the cloned repo: "cd pyqt_cython_and_c"
  • run cmake to create a makefile, with the install directory as our currenty working directory: "cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=.  cproject"
  • run the makefile to build the C code: "make"
  • run make install to install the library and headers to the CMAKE_INSTALL_PREFIX directory: "make install"
  • If this command worked (why wouldn't it?), and you should see files under lib/ and include/.  We'll use these in a moment.
This is just a Cmake taster.  See cmake.org for lots and lots of documentation.

The Cython wrapper

We now have a C library, but this isn't very useful from Python yet.  We need a way to wrap the C function in Cython so we can use it from Python.

PyQt suffers from Python's GIL the same as any Python application that uses threads.  This prevents more than one thread running at a time, to avoid any modification of state that could result in corruption or a crash.  Some Python functions will release the GIL, typically C extensions such as time.sleep() and various NumPy operations but pure Python code will generally not release the GIL.

In the demo I've created I used a Qthread to call a C function that is wrapped in a separate Python module.  The Python interpreter is locked for the entire duration of the C function call due to the GIL.  That means the GUI will appear frozen, or at least very jittery because the main UI thread isn't responding while the C function is being run.

We can make our demo fluid again by inserting time.sleep(0.1) in our Python callback.  This works because time.sleep() is a C extension that releases the GIL in the worker thread, giving the main UI thread a chance to catch up on it's queued signals while our worked thread takes a break (see Jesse Noller's excellent article).  It's ok if you don't like time.sleep, neither do I!

Lets find a way to do this without slowing down our code with a bunch of sleeps.  If we're calling a C function from Cython that doesn't modify any of our Python objects, just it's C objects, we can release the GIL.  This will let our two threads run in at the same time.  We can declare our C function as "nogil", then use a simple context handler to tell Cython to release the GIL when we're running our C function.

This Cython file uses "cimport" to get the C function declarations.  This is where we define that our C function can be run without the GIL:

Our Cython wrapper:

We're taking a very blunt force approach to error checking in our Cython wrapper.  C doesn't have exceptions, so we look for any exception in our Python code and return a non-zero value from our Cython code.  Obviously you could get a lot more creative with error checking.

Wait a minute, we're calling Python as a callback from our C function.  Won't this cause a crash if we modify a Python object?  Most likely, unless we reacquire the GIL before we run any Python code.  This is also straightforward, we just declare that our cdef'ed function needs to reacquire the GIL.  There's a couple ways of doing it, but the safest is to use the "with gil" syntax in the function definition.  Many thanks to the Cython devs for making this a simple task!

What is this code actually doing?  Let's recap.  We're using Cython to call our C function, supplying a Cython callback.  Since this is defined with "cdef" it's just a normal C function as far as our C library is concerned.  The key is that we're passing a Python object to the C code as a "void *".  Everything in Python is an object, so we can pass whatever we like - including functions, classes, methods, instances of classes, etc.  The Cython callback converts it back from a void * to a Python "callable" object and calls it, with the percentage complete as a argument.  Cython can handle conversion of C ints to Python ints, so there's no need for an explicit conversion.  The Cython docs explain how to wrap a C library, but I think it's nice to see a complete example.

You may be thinking the extra step of a Cython wrapper around a normal Python object is unecessarily complex.  Let me explain why I think it's a good approach.  Cython cdef'ed functions have to be cythonized and built using a compiler.  However, this approach lets us pass any arbitrary Python callable (function, even instance method) without recompiling.  This means we can dynamically run any Python code from our C code.  It's a very powerful feature.  In the demo we're passing the PyQt emit method on the task thread instance as a callback.  This is what updates the percentage complete of the progress bar.  It's very similar to this snippet.  Pretty compact I'd say:

Lets not forget that our Cython code gets translated to C then compiled.  We're using setuptools to build our Cython module (in a Python package).  Lets have a look at the file.  The important thing is we're using "libcproject.a" in the extra_objects option (this would be a lib or dll on Windows).  We've also added lib to library_dirs, and include to include_dirs.  This is the file we built with Cmake earlier:

Build the Cython module with the following command:
  • python setup.py build_ext --inplace
That's it, we've built everything we need.  Let's compare our two approaches.  Run "python progressbar.py" to launch the GUI.  There's two progress bars, the top one holds onto the GIL and the lower one releases it.  I wouldn't call myself a GUI programmer so be kind.  Run both to see how they compare, just not at the same time.  Hopefully it shows a smooth progress bar on the bottom.

This is just scratching the surface of Cmake and Cython.  Have a look at h5py for an example of a large and successful project using Cython to wrap a C library.

It's also worth mentioning multiprocessing.  This uses multiple processes instead of threads to avoid GIL.  I didn't use it because I wanted to use PyQt's signals/slots.  Multiprocessing works well for pure Python, especially embarassingly parallel tasks.  Parallel programming is a huge field so I'll leave it there for now.


1 comment: