开发者

Calling a C function with a timeout - ctypes

I use ctypes in a python project where I need to call some C functions which can take some hours for giving response. My problem is that I want to kill the function (from the python code) after a certain time even if the function has not finish the calculation.

I tried with multithread but it doesn't stop the C function. Here is my code.

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 exe开发者_开发问答cution 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"

It doesn't work : when I call iw_solve_wtimeout(10) ; the function doesn't stop after 10 seconds.

I tried with alarm but it doesn't stop the c function. Here is my code.

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;

This code also doesn't work : when I call iw_solve_wtimeout(10) ; the function doesn't stop after 10 seconds.

Do you have some ideas for doing it using ctypes?

Thanks a lot for your help.

Marc


That can't work because the Python code can't see into the C code to stop it running. That approach could only work with pure Python code.

Even if it would work, it would be the wrong way to stop a threads. You should think of threading as a co-operative endeavour. If you want a thread to stop, then you need to ask it to stop, and then wait until it has done so. Using co-operation rather than force avoids all sorts of horrible problems.

What you will need to do is to modify your C code and allow it to be signalled to cancel. The C code will need to regularly check for this signal. You could implement that with a ctypes callback or indeed many other ways.

But fundamentally you need to provide an explicit cancelling mechanism in your C code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜