python - 当 python 使用 "Python.h"调用该 c++ 进程时,如何在 python 中停止 c++ 进程

标签 python c++

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

这是装饰器:

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++ 函数,您需要向它发送一个信号。但仅仅发送一个信号是不够的。在 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 */
}

关于python - 当 python 使用 "Python.h"调用该 c++ 进程时,如何在 python 中停止 c++ 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856907/

相关文章:

Python/Django - 是否有类似于 Rails 的 assert_difference 的断言?

python - 无法使用 lxml 从 HTML 中提取值

c++ - 有没有办法找出我的操作系统在我的 RAM 中的位置?

c++ - 如何发出包含 'suspicious' 和 '-Wmain' 字样的警告?

c++ - C++中的多重继承

python - 如何将参数传递给 `transitions` 库中的 on_enter 回调?

python - 在 C++ 中嵌入 Python : Importing modules in python script works during one function call but not another

python - django queryset运行时-在恒定时间内获取第n个条目

c++ - 是否有人建议扩展 C++ 语言以消除 pimpl?

c++ - _pgmptr 发生了什么?