我正在编写一个C程序,它会生成多个C线程,每个线程都有一个Python子解释器。这些子解释器不共享任何可变的Python变量,它们是相互独立的。(它们确实可以只读访问从C程序中的main()函数暴露出来的公共PyObject(不可变))。
在Python 3.7或3.8中,是否可以做到这一点而不共享sub-interpreters之间的GIL锁呢?
以下是我尝试过的伪代码:
void *spawnInterpreter(void* p) {
…
PyThreadState* save_tstate = PyThreadState_Swap(NULL);
PyThreadState* tstate = Py_NewInterpreter();
PyThreadState_Swap(save_tstate);
//do some Python work (with variables that are NOT shared with other thread’s sub-interpreter
PyRun_SimpleString( . . .);
. . .
}
int main() {
...
pthread_create(&thread1, NULL, spawnInterpreter, “in1”);
pthread_create(&thread2, NULL, spawnInterpreter, "in2");
...
}
我可以在3.6中使其运作(无需在C线程中获取GIL或管理PyThreadState
),但在Python 3.7中我收到以下错误:
[New Thread 0x7ffff5f78700 (LWP 16392)]
Fatal Python error: drop_gil: GIL is not locked