0

我有一个用于 Python 的多线程 C 扩展。它使用 3 个线程将数据输出到 Python 中的类。

我正在使用 PyGILState_Ensure / PyGILState_Release API 来同步解释器调用。

扩展中可能存在一些线程在调用 PyGILState_Release 之前卡住并终止的情况。

无论如何我可以删除无效的 ThreadState 并继续使用线程 API 吗?

谢谢

4

2 回答 2

0

我不完全确定你是如何终止你的线程的,但是在我脑海中的实现中,你会破坏一个线程对象吗?在这种情况下,您释放析构函数中的锁......

于 2011-03-13T13:07:20.267 回答
0

我建议改变线程之间的交互模式。

您当前的实现似乎是这样工作的:

PyGILState_Ensure();
result = doDangerousThing(); // this could kill the thread
storeToPythonObject(result);
PyGILState_Release();

变体 A,显而易见:

result = doDangerousThing(); // this could kill the thread
PyGILState_Ensure();
storeToPythonObject(result);
PyGILState_Release();

变体 B,不太明显,见[1][2]的想法:

/* worker_thread.c */
result = doDangerousThing(); // this could kill the thread
putToLocklessQueue(result, *queue_in_main_thread);

/* main_thread.c */
if (hasItems(my_lockless_queue)) {
  PyGILState_Ensure();
  while (hasItems(my_lockless_queue)) {
    storeToPythonObject(popItem(my_lockless_queue));
  }
  PyGILState_Release();
  // sleep again here
}
于 2011-03-13T13:29:20.943 回答