类构造函数中的无限线程函数

时间:2016-11-12 01:37:20

标签: multithreading python-2.7

我有一个使用线程运行无限循环的类来填充线程安全队列:

from threading import Thread
from Queue import Queue
import time


class factory:
    def __init__(self):
        self.running = True
        self.q = Queue()
        t = Thread(target=self.count_indefinitely)
        t.start()
        time.sleep(3)
        print self.q.qsize()

    def count_indefinitely(self):
        i = 0
        while self.running:
            i += 1
            self.q.put(i)



if __name__ == '__main__':
    f = factory()
    time.sleep(2)
    print 'Hello!'
    f.running = False

代码到达我需要打印出队列大小的部分。但是,我无法在主函数中打印“hello”。我该怎么办呢?

0 个答案:

没有答案