Maison  >  Questions et réponses  >  le corps du texte

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

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

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

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

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

阿神阿神2717 Il y a quelques jours424

répondre à tous(3)je répondrai

  • 大家讲道理

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

    Voulez-vous dire que la fonction a effectué des tâches informatiques gourmandes en CPU ? Vous pouvez diviser la tâche et, après avoir exécuté une petite tâche, vérifier si elle expire et revenir si elle expire, sinon continuer.

    Supplément :
    Faisons ça

    # 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()
    
    
    
    

    Ma sortie ici est :

    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

    Je ne sais pas si le scénario auquel vous êtes confronté est comme celui-ci. Le problème spécifique doit être analysé en détail.

    répondre
    0
  • 天蓬老师

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

    module de signal :

    Référence http://blog.sina.com.cn/s/blo...

    répondre
    0
  • 怪我咯

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

    Regardez d'abord les emplacements de blocage possibles dans la fonction. S'il y a un délai d'attente, ajoutez un délai d'attente.

    répondre
    0
  • Annulerrépondre