这就是线程的用途。您可以同时运行工作线程和进度线程:import time
from threading import Thread
class WorkerThread(Thread):
def __init__(self, value=0):
super(WorkerThread, self).__init__()
self.value = value
def run(self):
while self.value < 1000:
self.value += 1
time.sleep(0.01)
class ProgressThread(Thread):
def __init__(self, worker):
super(ProgressThread, self).__init__()
self.worker = worker
def run(self):
while True:
if not self.worker.is_alive():
print 'Worker is done'
return True
print 'Worker is at', self.worker.value
time.sleep(1.0)
if __name__ == '__main__':
worker = WorkerThread()
progress = ProgressThread(worker)
worker.start()
progress.start()
progress.join()
命令的输出为:Worker is at 1
Worker is at 99
Worker is at 197
Worker is at 295
Worker is at 394
Worker is at 492
Worker is at 590
Worker is at 689
Worker is at 787
Worker is at 885
Worker is at 983
Worker is done
请注意,工作线程正在非常快地按1计数,但进度线程只是每秒报告一次进度。