You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.12子解释器多CPU利用问题及C++适配疑问

Python 3.12子解释器多核心利用问题

技术问题

  1. 子解释器线程与Python主线程同属一个进程,是否意味着子解释器只能使用主线程所在的CPU核心?
  2. 若确实如此,如何让子解释器利用全部可用CPU核心(现代硬件通常为8-16核)?

背景说明

我正在使用一款自带任务调度运行时的C++ reactor框架,该框架的多个reaction(方法)会被调度到运行时工作线程池中执行。我尝试通过subinterpreter C-API,借助Python子解释器功能实现reaction调用Python代码并更新reactor的PyThreadState,具体操作如下:

  1. 在顶层reactor中启动Python主解释器。
  2. 为每个子reactor初始化独立的Python PyThreadState*及拥有私有GIL的子解释器:
PyInterpreterConfig py_config = {
        .use_main_obmalloc = 0,
        .allow_fork = 0,
        .allow_exec = 0,
        .allow_threads = 1,
        .allow_daemon_threads = 0,
        .check_multi_interp_extensions = 1,
        .gil = PyInterpreterConfig_OWN_GIL,
};
this->py_status = Py_NewInterpreterFromConfig(
      &self->py_thread, &py_config);
assert(this->py_thread != NULL);
this->py_interp = PyThreadState_GetInterpreter(this->py_thread);
this->py_interp_id = _PyInterpreterState_GetIDObject(this->py_interp);
assert(this->py_interp_id != NULL);
PyObject *main_mod = _PyInterpreterState_GetMainModule(this->py_interp);
this->py_ns = PyModule_GetDict(main_mod);
Py_DECREF(main_mod);
Py_INCREF(this->py_ns);
const char* codestr =
    "id = \"Reactor_1\";"
    "import threading;"
    "print(f\"{id} @thread \" + str(threading.get_ident()));"
;
PyObject *result = PyRun_StringFlags(
    codestr, Py_file_input, this->py_ns, this->py_ns, NULL);

遇到的问题

  • 所有Python(子)解释器在调用各类reaction时均运行于同一线程;原本预期子解释器框架能让它们运行在不同核心(即不同线程)上(运行时调度reaction的工作线程本身是独立的)。
  • 在终结reaction中调用Py_EndInterpreter(this->py_thread);关闭子解释器时,若this->py_thread并非当前线程,可能导致系统崩溃。

恳请各位提供解决思路。


内容的提问来源于stack exchange,提问作者stustd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:05:01