当python使用“Python.h”调用该c++进程时,如何在python中停止一个c++进程

Posted

技术标签:

【中文标题】当python使用“Python.h”调用该c++进程时,如何在python中停止一个c++进程【英文标题】:How to stop a c++ process in python, when python invoke that c++ process using "Python.h" 【发布时间】:2019-11-14 12:34:26 【问题描述】:

在一个c++程序中,我使用“Python.h”来实现一个可以在python中使用的c++函数。 在 python 中,我希望这个 c++ 函数在有限的时间内运行。 所以,我在python中使用了一个函数装饰器来让c++函数在有限的时间内运行。如果函数超过给定的时间,它会引发一个 RuntimeError,然后我就让函数返回。 但是我的结果好像不太好,多次调用c++函数后,程序运行越来越慢,最后crash。

这是装饰器:

def set_timeout(num, callback):

    def wrap(func):

        def handle(signum, frame):  

            raise RuntimeError()

        def to_do(*args, **kwargs):
            try:
                signal.signal(signal.SIGALRM, handle) 
                signal.alarm(num)  
                print('start alarm signal.')
                r = func(*args, **kwargs)
                print('close alarm signal.')
                signal.alarm(0)  
                return r
            except RuntimeError as e:
                callback()

        return to_do

    return wrap

def after_timeout():

    return

这是python调用的带有装饰器的c++函数:

@set_timeout(3,after_timeout)
def pytowr_run(gait,tgt,time_interval,tm,posture=None,init_dic=):
    pos,cost,varDict = pytowr.run(gait,tgt[0],tgt[1],time_interval,tm,posture,init_dic)
    return pos

有没有办法让python调用的c++函数在python中停止运行?

【问题讨论】:

如果您想停止一个进程,那么在该进程中运行的程序是用哪种编程语言创建的并不重要。从这个意义上说,没有“C++ 进程”这样的东西。作为这里的新用户,请同时使用tour并阅读How to Ask。 【参考方案1】:

要停止 c++ 函数,您需要向它发送一个信号。但是仅仅发送一个信号是不够的。在 c++ 函数中,您可能需要设置一些中断点来检查是否发送了信号。示例:

#include <csignal>
#include <atomic>

constexpr int SIGALRM = 14;
std::atomic_bool signal_received;

void signal_handler(int signal) 
    // check 'signal' if necessary
    signal_received.store(true);


void config()  //call it at some start point...
    signal_received.store(false);
    std::signal(SIGALRM, signal_handler);


void your_function(/*args*/) 
    /* do some work */
    if (signal_received.load()) return; //interrupt point. Exiting your c++ function...
    // the interrupt point must be placed in a strategic place
    /* maybe more work */

【讨论】:

【参考方案2】:

如果我理解你的目标,我认为一个更好的解决方案是调用 C/C++ 函数并将分配的时间传递给 C/C++ 函数,而不是尝试从 python 中杀死函数,这是可行的,但会生成代码更难阅读和调试。

#include datetime.h 
PyDateTime_IMPORT

bool your_function(passed_in_vars, start_time * PyDateTime_DateTime allotted_time* int ) 


    kill_time = PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) + allotted 
    /* do some work */
    if ( allotted_time > kill_time  ) 
        return; //interrupt point. Exiting your c++ function...

    //do more work... 

这使得代码更容易在 python 端没有循环或等待状态,并使 C++ 端更容易知道何时终止函数并触发任何清理代码。

在 C++ 方面更容易找到瓶颈。

【讨论】:

以上是关于当python使用“Python.h”调用该c++进程时,如何在python中停止一个c++进程的主要内容,如果未能解决你的问题,请参考以下文章

将 Python 添加到 C++:找不到 Python.h

在 QT Creator 中使用 C++ 调用 Python 脚本

如何在 C++ 中调用大型 python 脚本?

C++多线程中调用python api函数

在 C++ 程序中调用 Python 函数

ROS工程中C++调用python函数