V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
uurun
V2EX  ›  程序员

请教大家一个 pybind11 的问题

  •  
  •   uurun · Aug 9, 2022 · 1353 views
    This topic created in 1357 days ago, the information mentioned may be changed or developed.

    请教大家一个 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 replies    2022-08-09 14:26:51 +08:00
    ysc3839
        1
    ysc3839  
       Aug 9, 2022   ❤️ 1
    嵌入使用 CPython 的时候,主线程是一直持有 GIL 的,如果主线程没有调用 Python 代码,需要手动释放 GIL ,其他 Python 线程才能运行。在 while 前后分别加上 Py_BEGIN_ALLOW_THREADS 和 Py_END_ALLOW_THREADS 即可。
    https://stackoverflow.com/a/25819019
    uurun
        2
    uurun  
    OP
       Aug 9, 2022
    @ysc3839 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   997 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 22:25 · PVG 06:25 · LAX 15:25 · JFK 18:25
    ♥ Do have faith in what you're doing.