请教大家一个 pybind11 的问题

2022-08-09 10:38:28 +08:00
 uurun

请教大家一个 pybind11 的问题, 我的主程序是 c++写的, 将 python 作为脚本调用, 目前有个问题是加载 python 脚本之后, python 里面的线程就停止了, 代码如下:

#include <thread>
#include <pybind11.h>

const char* code = R"(
import sys, os, time, threading
print("hello")
def run():
    while True:
        print("abc")
        time.sleep(1)

t = threading.Thread(target=run)
t.start()
)";

void main(int args, char* argv[]) 
{
    pybind11::scoped_interpreter scoped(false);
    pybind11::exec(code);
    
    while (true) 
    {
    	std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
    return 0;
}

上面的代码只会输出 1 个 abc. 有什么办法能够让 python 的线程持续运行呢?

946 次点击
所在节点    程序员
2 条回复
ysc3839
2022-08-09 11:16:52 +08:00
嵌入使用 CPython 的时候,主线程是一直持有 GIL 的,如果主线程没有调用 Python 代码,需要手动释放 GIL ,其他 Python 线程才能运行。在 while 前后分别加上 Py_BEGIN_ALLOW_THREADS 和 Py_END_ALLOW_THREADS 即可。
https://stackoverflow.com/a/25819019
uurun
2022-08-09 14:26:51 +08:00
@ysc3839 谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/871609

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX