November 23rd 2007 03:18 pm
Enabling thread support in SWIG and Python
I was looking for some days in SWIG documentation how I could release the GIL (Global Interpreter Lock) with SWIG. There were some macros defined in the generated code, but none was used in any place.
In fact, I just had to enable the thread support with an additional argument (-threads) and now every wrapped function releases the GIL before it is called, but that does not satisfy me. Indeed, some of my wrappers must retain the GIL while they are used (see this item). So here are the features that can be used :
- nothread enables or disables the whole thread lock for a function :
- %nothread activates the nothread feature
- %thread disables the feature
- %clearnothread clears the feature
- nothreadblock enables or disables the block thread lock for a function :
- %nothreadblock activates the nothreadblock feature
- %threadblock disables the feature
- %clearnothreadblock clears the feature
- nothreadallow enables or disables the allow thread lock for a function :
- %nothreadallow activates the nothreadallow feature
- %threadallow disables the feature
- %clearnothreadallow clears the feature
When the whole thread lock is enabled, the GIL is locked when entering the C function (with the macro SWIG_PYTHON_THREAD_BEGIN_BLOCK). Then it is released before the call to the function (with SWIG_PYTHON_THREAD_BEGIN_ALLOW), retained after the end (SWIG_PYTHON_THREAD_END_ALLOW) and finally it is released when exiting the function (SWIG_PYTHON_THREAD_END_BLOCK), after all Python result variables are created and/or modified.
2 Comments »
2 Responses to “Enabling thread support in SWIG and Python”
Leave a Reply
You must be logged in to post a comment.


Camus SoNiCo on 15 Feb 2008 at 5:46 pm #
Thanks, i always come back to your article since i never remember those
Do you know if there is any way to apply the feature to an entire class?
Matt on 20 Feb 2008 at 9:47 am #
Thanks for your comment
You should be able to specify a whole class and only this class by something like :
%thread MyClass;
I didn’t test it (not time at the moment), but it should behave like any other feature.