Search code examples
multithreadingpython-2.7python-c-api

How to execute PyObject_CallObject() in two different threads simultaneously?


I have two functions running on two threads simultaneously. Both functions call this method PyObject_CallObject(pFunc,pArgs) to execute two different python functions. But i am getting access violation reading location exception when i try to do so. pFunc and pArgs used in both function are local to that function and there is no shared data. Still how i get exception?


Solution

  • That's not possible. You must acquire the global interpreter lock (GIL) before you call any Python CAPI function. There are just a few functions that can be called without the GIL.

    https://docs.python.org/2/c-api/init.html#thread-state-and-the-global-interpreter-lock

    The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice.