后来在Python中杀死线程

问题描述:

我有一个带有线程的Python代码,我需要如果在例如1小时内线程没有完成,完成所有线程并完成脚本,并且如果小时未完成等待我所有的线程都完成了。后来在Python中杀死线程

我试着用守护线程和一小时的睡眠,如果小时已经完成,使用:sys.exit()但它对我不起作用,因为总是等到我的睡眠线程,然后我的脚本等到线程完成并且sys.exit()不起作用。

import socket, threading, time, sys 
from sys import argv 
import os 

acc_time=0 
transactions_ps=5 

ins = open(sys.argv[1],'r') 
msisdn_list = [] 
for line in ins: 
    msisdn_list.append (line.strip('\n')) 
    # print line 
ins.close() 


def worker(msisdn_list): 
    semaphore.acquire() 
    global transactions_ps 
    print " ***** ", threading.currentThread().getName(), "Lanzado" 
    count=1 
    acc_time=0 
    print "len: ",len(msisdn_list) 
    for i in msisdn_list: 
     try: 
      init=time.time() 
      time.sleep(2) 
      print "sleeping...",i 
      time.sleep(4) 
      final=time.time() 
      acc_time = acc_time+final-init 
      print acc_time 
     except IOError: 
       print "Connection failed",sys.exc_info()[0] 

    print "Deteniendo ",threading.currentThread().getName() 
    semaphore.release() 
def kill_process(secs_to_die): 
    time.sleep(secs_to_die) 
    sys.exit() 

seconds_to_die=3600 

thread_kill = threading.Thread(target = kill_process, args=(seconds_to_die,)) 
thread_kill.start() 

max_con=5 
semaphore = threading.BoundedSemaphore(max_con) 
for i in range(0,28,transactions_ps): 
    w = threading.Thread(target=worker, args=(msisdn_list[i:i+transactions_ps-1],)) 
    w.setDaemon(True) 
    w.start() 

如何能做到这一点

+0

此代码工作正常,我 - 这里等到'secs_do_die'已经过去了,那么整个脚本退出。这是你使用的实际代码吗? ().display()' – dano 2014-08-30 14:20:17

+0

'以open(sys.argv [1])作为文件:msisdn_list = file.read()。splitlines()' – jfs 2014-08-31 10:52:13

您可参照本实施KTHREAD的:

http://python.todaysummary.com/q_python_45717.html

+0

您应该在答案中添加一些信息,以概括您所包含的链接中所说的内容。否则,如果该链接死亡,这个答案将变得毫无用处。或者,只需将此添加为问题的评论即可。 – dano 2014-08-30 14:27:49

变化最小,以你的代码,将解决这个问题是threading.Barrier

barrier = Barrier(number_of_threads, timeout=3600) 
# create (number_of_threads - 1) threads, pass them barrier 
# each thread calls barrier.wait() on exit 
barrier.wait() # after number_of_threads .wait() calls or on timeout it returns 

更简单的选择是使用multiprocessing.dummy.Pool创建守护线程:

from multiprocessing.dummy import Pool # use threads 

start = timer() 
endtime = start + 3600 
for result in pool.imap_unordered(work, args): 
    if timer() > endtime: 
     exit("timeout") 

代码不超时,直到一个工作项目完成后,即预计从列表处理单个项目并不需要很长时间。

完整的示例:

#!/usr/bin/env python3 
import logging 
import multiprocessing as mp 
from multiprocessing.dummy import Pool 
from time import monotonic as timer, sleep 

info = mp.get_logger().info 

def work(i): 
    info("start %d", i) 
    sleep(1) 
    info("end %d", i) 

seconds_to_die = 3600 
max_con = 5 
mp.log_to_stderr().setLevel(logging.INFO) # enable logging 
pool = Pool(max_con) # no more than max_con at a time 
start = timer() 
endtime = start + seconds_to_die 
for _ in pool.imap_unordered(work, range(10000)): 
    if timer() > endtime: 
     exit("timeout")