2011-03-09 37 views
2

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

我尝试了多线程,但它并没有停止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秒后不停止。

我尝试了警报,但它并没有停止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的一些想法?

非常感谢你的帮助。

马克

回答

0

这不能工作,因为Python代码看不进的C代码停止运行它。该方法只能使用纯Python代码。

即使它能工作,停止线程也是错误的方法。你应该把线程看作是一种合作的努力。如果你想要一个线程停止,那么你需要让它停下来,然后等到它完成。使用合作而不是武力可以避免各种可怕的问题。

什么,你需要做的就是修改C代码,并允许它被通知给取消。 C代码将需要定期检查这个信号。你可以用ctypes回调或其他许多方法实现它。

但从根本上讲,你需要提供一个明确的解除机构在C代码。