在一行中打印多线程

时间:2018-03-22 13:00:16

标签: python multithreading python-3.x

我想用多线程打印一行。我创建了一个创建新线程的类来打印它:

class Printer(threading.Thread):
    def __init__(self, count1, count2):
        threading.Thread.__init__(self)
        self.count1 = count1
        self.count1 = count1

    def run(self):
        while True:
            to_print = '\rCount1: {}      Count2: {}'.format(self.count1, self.count1)
            sys.stdout.write(to_print)
            sys.stdout.flush()
            time.sleep(5)

然后我通过以下方式运行:

class ThreadPool(object): 
    def __init__(self,args):

    for _ in range(num_threads):
        worker = Worker(self.__queue) #Worker is a class run some tasks.
        if False is worker.isAlive():
            worker.setDaemon(True)
            worker.start()

    s = ThreadWriterSuccess(self.__write_q, 'success.txt')
    s.setDaemon(True)
    s.start()

    f = ThreadWriterFailed(self.__failed_q, 'failed.txt')
    f.setDaemon(True)
    f.start()

    p = Printer(s.counter, f.counter)
    p.setDaemon(True)
    p.start()

class ThreadWriterSuccess(threading.Thread):
    "Write Success"

    def __init__(self, queue, outputPath):
        self.q = queue
        self.outputPath = outputPath
        threading.Thread.__init__(self)
        self.counter = 0

    def run(self):
        """
        Write data in queue to file
        :return: None
        """
        while True:
            toWrite = self.q.qsize()
            self.counter += toWrite
            outputFile = open(self.outputPath, 'a+')
            for i in range(toWrite):
                data = self.q.get()
                content = 'SUCCESS | {0}\n'.format(data)
                outputFile.write(content)
                self.q.task_done()
            outputFile.close()
            time.sleep(10)


class ThreadWriterFailed(threading.Thread):
    "Write failed"

    def __init__(self, queue, outputPath):
        self.q = queue
        self.outputPath = outputPath
        threading.Thread.__init__(self)
        self.counter = 0

    def run(self):
        """
        Write data in queue to file
        :return: None
        """
        while True:
            toWrite = self.q.qsize()
            self.counter += toWrite
            # print('Die: {}'.format(self.counter), end='\r')
            outputFile = open(self.outputPath, 'a+')
            for i in range(toWrite):
                data = self.q.get()
                content = 'FALSE: | {0}\n'.format(data)
                outputFile.write(content)
                self.q.task_done()
            outputFile.close()
            time.sleep(5)

注意:s.counterf.counterThreadWriterSuccessThreadWriterFailed类中的值。

但是,当我运行程序时,Printer类仅在第一次运行并打印。它没有再次运行。我怎么解决这个问题?感谢。

0 个答案:

没有答案
相关问题