簡體   English   中英

python看門狗線程

[英]python watchdog for threads

我正在編寫一個簡單的應用程序,該程序從文件中讀取(大約一百萬)行,然后將這些行復制到列表中,如果下一行與之前的行不同,它將運行一個線程,以對該列表進行處理。 線程作業基於tcp套接字,通過telnet lib發送和接收命令。

有時我的應用程序掛起,什么也不做。 我包裝到try-except語句中的所有telnet操作,也讀寫套接字都具有超時。

我考慮過編寫看門狗,它將執行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)

此致J

過去,我已經成功使用了以下代碼(來自我編寫的python 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM