2011-03-09 2 views
2

저는 파이썬 프로젝트에서 ctypes를 사용합니다. 여기서는 응답을하기 위해 몇 시간이 걸리는 C 함수를 호출해야합니다. 내 문제는 함수 (파이썬 코드에서) 특정 시간 후에 함수를 끝내지 않은 경우에도 함수를 죽이고 싶다는 것입니다.시간 초과가있는 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를 사용하여 아이디어를 얻었습니까?

도움을 주셔서 감사합니다.

마크는

파이썬 코드는 C 코드로 볼 수 없기 때문에 작동하지 않을 수

답변

0

실행을 중지합니다. 이 접근법은 순수한 Python 코드에서만 작동합니다.

작동하는 경우에도 스레드를 중지하는 것은 잘못된 방법 일 수 있습니다. 스레딩은 협동 작업으로 생각해야합니다. 스레드가 멈추길 원한다면 멈추라는 요청을하고 나서 끝날 때까지 기다려야합니다. 힘보다는 협력을 사용하면 모든 종류의 끔찍한 문제를 피할 수 있습니다.

당신이해야 할 일은 C 코드를 수정하고 취소 신호를 보내도록 허용하는 것입니다. C 코드는이 신호를 정기적으로 확인해야합니다. ctypes 콜백 또는 실제로 많은 다른 방법으로 구현할 수 있습니다.

근본적으로 C 코드에서 명시적인 취소 메커니즘을 제공해야합니다.