Skip to main content
 首页 » 编程设计

python之超时调用 C 函数之ctypes

2025年05月04日9duanxz

我在一个 python 项目中使用 ctypes,我需要调用一些 C 函数,这可能需要几个小时才能给出响应。我的问题是我想在一段时间后终止函数(从 python 代码),即使函数还没有完成计算。

我尝试使用多线程,但它不会停止 C 函数。这是我的代码。

lib_iw = cdll.LoadLibrary("./iw.so") 
 
iw_solve = lib_iw.solve_iw # the C function which can take some hours for responding 
iw_solve.restype = c_void_p 
iw_solve.argtypes = [c_void_p] 
 
def iw_solve2() : 
    iw_solve(None) 
 
def iw_solve_wtimeout(time_out) : # the function which thow $iw_solve and kill the execution of $iw_solver after $time_out seconds (but it doesn't work) 
    t_solve = threading.Thread(None,iw_solve2,None,(),None) 
    t_solve.run() 
    t = time.time() 
 
    while(t_solve.is_alive() and ((time.time() - t) < 2)) : 
        time.wait(0.3) 
 
    if(t_solve.is_alive()) : 
        t_solve._Thread__stop() 
        print "iw_solve was killed" 
    else : 
        print "iw_solve has respond" 

它不起作用:当我调用 iw_solve_wtimeout(10) 时;该功能不会在 10 秒后停止。

我试过 alarm 但它不会停止 c 函数。这是我的代码。

lib_iw = cdll.LoadLibrary("./iw.so") 
 
iw_solve = lib_iw.solve_iw # the C function which can take some hours for responding 
iw_solve.restype = c_void_p 
iw_solve.argtypes = [c_void_p] 
 
def iw_solve_withtimeout(time_out) : # the function which thow $iw_solve and kill the execution of $iw_solver after $time_out seconds (but it doesn't work) 
    signal.signal(signal.SIGALRM, handler) 
    signal.alarm(time_out) 
    try : 
        print "debut iw_solve" 
        signal.alarm(time_out) 
        iw_solve(None) 
    except Exception, exc: 
        print exc 
        return None; 

此代码也不起作用:当我调用 iw_solve_wtimeout(10) 时;该功能不会在 10 秒后停止。

对于使用 ctypes 做这件事,您有什么想法吗?

非常感谢您的帮助。

马克

请您参考如下方法:

这行不通,因为 Python 代码无法查看 C 代码以阻止它运行。这种方法只能用于纯 Python 代码。

即使可行,停止线程的方法也是错误的。您应该将线程视为一种合作努力。如果你想让一个线程停止,那么你需要让它停止,然后等待直到它停止。使用合作而不是武力可以避免各种可怕的问题。

您需要做的是修改您的 C 代码并允许它发出取消信号。 C 代码需要定期检查此信号。您可以使用 ctypes 回调或许多其他方式来实现它。

但从根本上说,您需要在 C 代码中提供明确的取消机制。