V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
uurun
V2EX  ›  程序员

请教大家一个 pybind11 的问题

  •  
  •   uurun · 2022-08-09 10:38:28 +08:00 · 933 次点击
    这是一个创建于 597 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教大家一个 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 的线程持续运行呢?

    2 条回复    2022-08-09 14:26:51 +08:00
    ysc3839
        1
    ysc3839  
       2022-08-09 11:16:52 +08:00   ❤️ 1
    嵌入使用 CPython 的时候,主线程是一直持有 GIL 的,如果主线程没有调用 Python 代码,需要手动释放 GIL ,其他 Python 线程才能运行。在 while 前后分别加上 Py_BEGIN_ALLOW_THREADS 和 Py_END_ALLOW_THREADS 即可。
    https://stackoverflow.com/a/25819019
    uurun
        2
    uurun  
    OP
       2022-08-09 14:26:51 +08:00
    @ysc3839 谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1197 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:16 · PVG 07:16 · LAX 16:16 · JFK 19:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.