Home  >  Q&A  >  body text

线程 - Python如何实现让一个函数超时退出?

需求: 多个子线程同时调用a函数处理数据,如何实现让a函数超时之后return或者raise?

1 signal不能在子线程中使用,pass
2 把函数扔到进程里,开销太大,pass
3 把函数扔到单独线程里,改编进程类另其可接受终止信号,再开另外一个线程做监控,不易实现,且个人认为杀掉进程对系统资源的风险很大.

有没有什么好的解决方案,或者已有类库里面的timeout参数都是如何实现的呢?gevent有没有什么好的线程终止方案?

参考:
http://stackoverflow.com/ques...

阿神阿神2765 days ago462

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 09:17:49

    Do you mean that the function is always doing CPU-intensive computing tasks? You can split the task, and after executing a small task, check whether it times out, and return if it times out, otherwise continue.

    Supplement:
    Let’s do this

    # coding=utf-8
    import datetime
    import time
    
    
    def run(n):
        s = 0
        for i in range(0, n):
            for j in range(0, n):
                s += 1
        return s
    
    
    def run_within_time(n, time_in_millisecond):
        s = 0
    
        start_time = long(time.time() * 1000)
        for i in range(0, n):
            for j in range(0, n):
                s += 1
            elapsed = long(time.time() * 1000) - start_time
            # 做完一部分任务后,判断是否超时
            if elapsed >= time_in_millisecond:
                s = -1
                break
        return s
    
    
    num = 10000
    print long(time.time() * 1000)
    print datetime.datetime.now()
    print run(num)
    print 'run :'
    print datetime.datetime.now()
    print run_within_time(num, 200)
    print 'run_within_time:'
    print datetime.datetime.now()
    
    
    
    

    My output here is:

    2016-07-28 22:25:33.271503
    100000000
    run :
    2016-07-28 22:25:37.473611
    -1
    run_within_time:
    2016-07-28 22:25:37.673276

    I don’t know if the scenario you are facing is like this. The specific problem needs to be analyzed in detail.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:17:49

    signal module:

    Reference http://blog.sina.com.cn/s/blo...

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:17:49

    First look at the possible blocking places in the function. If there is a timeout, add a timeout.

    reply
    0
  • Cancelreply