2012-12-07 89 views
0

我正在编写简单的应用程序,它从文件读取(大约一百万)行,将这些行复制到列表中,并且如果下一行将不同,那么之前它会运行一个线程,以使用该列表执行一些工作。线程作业基于tcp套接字,通过telnet lib发送和接收命令。用于线程的python看门狗

有时我的应用程序挂起和什么也不做。我将所有telnet操作都包含在try-except语句中,读写套接字也有超时。

我想过要写看门狗,它会执行sys.exit()或类似于挂起的条件。但是,现在我正在考虑如何创建它,但仍然不知道如何去做。所以如果你能跟踪我,那会很好。

该文件我创建40个线程。伪代码如下:

lock = threading.Lock() 
no_of_jobs = 0 

class DoJob(threading.Thread): 
    def start(self, cond, work): 
     self.work = work 
     threading.Thread.start(self) 
    def run(self) 
     global lock 
     global no_of_jobs 
     lock.acquire() 
     no_of_jobs += 1 
     lock.release() 

     # do some job, if error or if finished, decrement no_of_jobs under lock 
     (...) 
main: 
#starting conditions: 
with open(sys.argv[1]) as targetsfile: 
    head = [targetsfile.next() for x in xrange(1)] 
    s = head[0] 

    prev_cond = s[0] 
    work = [] 

for line in open(sys.argv[1], "r"): 
    cond = line([0]) 
    if prev_cond != cond: 
     while(no_of_jobs>= MAX_THREADS): 
      time.sleep(1) 

     DoJob(cond, work) 
     prev_cond = cond 
     work = None 
     work = [] 
    work.append(line) 

#last job: 
     DoJob(cond, work) 

while threading.activeCount() > 1: 
    time.sleep(1) 

问候 Ĵ

+1

看起来凌乱。我怪怪的线程 –

+0

stick logging.debug(“我现在在哪里”)在任何地方,看看会发生什么。这是我唯一能够解决“幕后”线索的问题。 –

+0

听起来几乎像http://packages.python.org/Pyro4/? (或者甚至兔子和芹菜) –

回答

0

我在过去已经成功地使用类似的代码如下(从巨蟒-3程序我写的):

import threading 

def die(): 
    print('ran for too long. quitting.') 
    for thread in threading.enumerate(): 
      if thread.isAlive(): 
        try: 
          thread._stop() 
        except: 
          pass 
    sys.exit(1) 


if __name__ == '__main__': 
    #bunch of app-specific code... 

    # setup max runtime 
    die = threading.Timer(2.0, die) #quit after 2 seconds 
    die.daemon = True 
    die.start() 

    #after work is done 
    die.cancel()