0

I'm trying to use pythonnet (C# library) from multiple threads, but it deadlocks. The following seems to be the procedure for calling CPython from that library:

Py_InitializeEx(0); // Initialize CPython
if (PyEval_ThreadsInitialized() == 0)
    PyEval_InitThreads();
// ---------------------------
gs = PyGILState_Ensure();
// Execute some Python code here
PyGILState_Release(gs);

However, when running this again from a different thread (not main thread) it deadlocks:

gs = PyGILState_Ensure(); // Deadlocks!
// Execute some Python code here
PyGILState_Release(gs);

What is the proper way to call CPython from multiple threads?

The following question:

Embedding python in multithreaded C application

seems to be related, but I am non the wiser in what the "correct" approach is?

ks1322
  • 33,961
  • 14
  • 109
  • 164
HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • 1
    The GIL is a *Global* interpreter lock. You cannot have two threads executing python code at the same time. – Botje Oct 17 '19 at 13:55
  • @Botje I know that, but as I understand it, the GIL is a lock -- a mutex -- which goal is to prevent that from happening. It should block, but not deadlock. – HelloWorld Oct 17 '19 at 14:42
  • How did you diagnose this as a deadlock? That involves two threads holding locks waiting for each other's locks to be unlocked. – Botje Oct 18 '19 at 11:44

0 Answers0