在Python中优雅地杀死一个线程

时间:2017-06-07 15:10:58

标签: python multithreading python-2.7 cherrypy

我在按Ctrl + C时尝试终止一个线程。我创建了一个类来处理我希望线程定期执行的所有操作。问题是当KeyboardInterrupt被引发(或SIGINT)时,循环成功停止,但整个程序冻结(我使用cherrypy作为Web服务器)。我环顾四周,找不到解决方案。有人可以开导我吗?

代码:

main.py

from KeywordWorker import main as worker

SMBinWorker = worker.KeywordHandler(SMBinDir, sqlitePath)
SMBinWorker.run()
signal(SIGINT, SMBinWorker.setFlag)

我的目标代码:

from os import listdir
from os.path import isfile
from os.path import join as osjoin
from time import sleep
from signal import signal, SIGINT

from extentions import *

import threading as mp

class KeywordHandler:
def __init__(self, path_to_files, sqlite_path):
    self.shutdown_flag = mp.Event()
    self.pathToFiles = path_to_files
    self.sqlitePath = sqlite_path
    self.queue = list()
    # Files Already Processed
    self.filesProcessed = set()

# start Process
def run(self):
    self.prc = mp.Thread(target=self.worker)
    self.prc.start()

def setFlag(self, foo, bar):
    print "\n  Shutting down Keyword Handler Gracefully.."
    self.shutdown_flag.set()
    self.prc.join()

# determines what to do with file
def extentionResolver(self, fileName):
    # deal with file extention
    pass

# return file count on directory
def getFileCount(self):
    return len([f for f in listdir(self.pathToFiles) if isfile(osjoin(self.pathToFiles, f))])

# return files names
def getFileList(self):
    return [f for f in listdir(self.pathToFiles) if isfile(osjoin(self.pathToFiles, f))]

# reset queue
def reset(self):
    self.queue = list()
    self.filesProcessed = set()

# compares directory to queue
def updateQueue(self):
    # update queue
    pass

# Deal with files in queue    
def resolveQueue(self):
    # resolve queue
    # loop through each file, and at the end of the loop, check shutdown_flag 
    pass


def worker(self):
    while not self.shutdown_flag.is_set():
        if self.getFileCount() > len(self.filesProcessed):
            # Check what's new
            self.updateQueue()
            sleep(0.2)
            # Process queue
            self.resolveQueue()

        sleep(10)

0 个答案:

没有答案