2014-08-30 2 views
1

파이썬 코드가 있습니다. 예를 들어 1 시간이면 스레드가 완료되지 않고 모든 스레드가 끝나고 스크립트가 끝납니다. 내 모든 스레드가 완료됩니다.파이썬에서 나중에 스레드를 죽이십시오

나는 잠을 자다가 시간을 보내고, 시간이 끝나면 : 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'이 경과 한'때까지, 다음 전체 스크립트가 종료 기다립니다. 이 코드가 사용중인 실제 코드입니까? 파일로 열기 (sys.argv [1]) : – dano

+0

'with open (sys.argv [1]) : msisdn_list = file.read(). splitlines()' – jfs

답변

0

당신은 kthread는이 구현에 참조 할 수 있습니다 :

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

+0

포함 된 링크에서 말한 내용을 요약 한 정보를 응답에 추가해야합니다. 그렇지 않으면 링크가 끊어지면이 대답은 쓸모 없게됩니다. 또는 질문에 주석으로 추가하십시오. – dano

2

문제를 해결하는 것입니다 코드에 대한 최소한의 변화가 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") 
관련 문제