我正在创建一个C ++ GUI应用程序,其按钮需要执行Python类中的线程化函数。我需要的两个按钮实际上是“启动python线程”和“停止python线程”。
问题在于boost :: python将调用python函数,但在C ++ boost :: 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")
import time
import Ticker as tick
ticker = tick.Ticker()
ticker.start()
time.sleep(10)
ticker.stop()
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
#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;
}
ticking startedTue Jun 4 20:35:17 2019
ticking stopped
如上所述,C ++ main不会输出python main会输出的10个预期时间戳。