2

All python thread(in CPython) are under GIL.

What if the thread is created by ctypes?

For example, python just calls the below function through C Library and the function create a thread in C area not python.

#include<thread>
int createUnitTestThread(int sasAddr){  
    sasEngine->thread = new std::thread(....);
    return 0;
}

Is it the same or not ?

SangminKim
  • 8,358
  • 14
  • 69
  • 125

1 Answers1

4

It's not like threads are under the GIL, operations in the Python interpreter are (including stuff like the fetch and execution of most opcodes, so that's why threads that execute Python code run mostly interlocked).

Your C++ thread will run free as long as it doesn't call back functions in the Python interpreter (either user callbacks or functions coming from Python.h).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • Thank you for your answer! One more question, even though the `C++ thread` is not under `GIL`, it is still running on the `python interpreter` having the same `PID`, right ? – SangminKim Mar 24 '16 at 06:32
  • I'm pretty sure that Bad Things™ will happen if you call Python from a thread not created by python, unless you explicitly register it somehow. – o11c Mar 24 '16 at 06:33
  • @asleea: being a thread, yes (well, under Linux is a bit more confused because everything is actually a task, so you could argue it has a different process id, but whatever). – Matteo Italia Mar 24 '16 at 06:41
  • @o11c: probably, although I'm not sure, I never called python.h stuff explicitly from a thread; anyhow, the bit of advice is mostly useful for callbacks (which are supported and routinely used with ctypes). – Matteo Italia Mar 24 '16 at 06:43
  • 4
    @o11c, a thread can get a `PyThreadState` and acquire the GIL by calling `PyGILState_Ensure`, which is what ctypes callbacks do before calling the target Python function. – Eryk Sun Mar 24 '16 at 09:49
  • @SangminKim Yes, they shared the same pid, roughly we should treat the dynamic library as the part of procedure, although they have some special points – Bingoabs May 20 '21 at 03:02