我在一个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的一些想法?
非常感谢你的帮助。
马克