使用boost :: python从C ++调用时,嵌入式Python线程会提前终止。

时间:2019-06-05 00:47:11

标签: python boost python-multithreading boost-python boost-thread

我正在创建一个C ++ GUI应用程序,其按钮需要执行Python类中的线程化函数。我需要的两个按钮实际上是“启动python线程”和“停止python线程”。

问题在于boost :: python将调用python函数,但在C ++ boost :: python调用返回后,将不允许python线程继续运行。结果,python线程似乎在启动后立即终止。我怎样才能使该线程保持活动状态?

Python类

import time
import threading

class Ticker():
    def __init__(self):
        self.is_ticking = False

    def start_ticking(self):
        self.is_ticking = True
        while self.is_ticking:
            print(time.ctime())
            time.sleep(1.0)

    def stop(self):
        self.is_ticking = False
        self.t.join()
        print("ticking stopped")

    def start(self):
        self.t = threading.Timer(0, self.start_ticking)
        self.t.start()
        print("ticking started")

Python主程序

import time
import Ticker as tick

ticker = tick.Ticker()

ticker.start()

time.sleep(10)

ticker.stop()

良好的Python输出

ticking started
Tue Jun  4 20:32:05 2019
Tue Jun  4 20:32:06 2019
Tue Jun  4 20:32:07 2019
Tue Jun  4 20:32:08 2019
Tue Jun  4 20:32:09 2019
Tue Jun  4 20:32:10 2019
Tue Jun  4 20:32:11 2019
Tue Jun  4 20:32:12 2019
Tue Jun  4 20:32:13 2019
Tue Jun  4 20:32:14 2019
ticking stopped

C ++ main

#include <boost/python.hpp>
#include <boost/chrono.hpp>
#include <boost/thread/thread.hpp> 

int main(int argc, char *argv[]) {

    Py_Initialize();

    boost::python::object ticker_module = boost::python::import("Ticker");
    boost::python::object ticker = ticker_module.attr("Ticker")();

    ticker.attr("start")();

    boost::this_thread::sleep_for(boost::chrono::seconds(10));

    ticker.attr("stop")();

    return 0;
}

C ++输出错误

ticking startedTue Jun  4 20:35:17 2019

ticking stopped

如上所述,C ++ main不会输出python main会输出的10个预期时间戳。

0 个答案:

没有答案