Python学习----多线程处理工作队列

来源:互联网 发布:淘宝店铺扫店软件 编辑:程序博客网 时间:2024/05/21 17:40

目标

开始学习Python,练手
建立一个任务队列,添加一堆任务,然后开启多个线程去处理队列里的任务

代码

#创建工作队列for i in range(100000):    MyWorkThread.workQueue.put(work)
#启动多线程,处理工作队列里的内容threads = []for i in range(THREAD_NUM):    thread = MyWorkThread.MyWorkThread()    thread.start()    threads.append(thread)#等待队列清空while not MyWorkThread.workQueue.empty():    time.sleep(2)    pass#MyWorkThread.workQueue.join()#通知线程是时候退出MyWorkThread.exitAllThread()print('触发退出所有工作线程')#等待所有线程完成退出for t in threads:    t.join()
#!/usr/bin/python#coding=utf-8import threadingimport timeimport tracebackimport osimport Queueclass MyWorkThread(threading.Thread):    def __init__(self,):        threading.Thread.__init__(self)    def run(self):        global workQueue        global exitFlag        globalLock.acquire()        loop = exitFlag        globalLock.release()        while not loop:            try:                #任务并运行                work = workQueue.get(False)                work.run()                del work            except Queue.Empty:                time.sleep(0.5)            except Exception as e:                print('ERROR:',e)                print('traceback.format_exc():\n%s' % traceback.format_exc())                time.sleep(0.5)                os._exit(0)            globalLock.acquire()            loop = exitFlag            globalLock.release()        print('线程{}结束'.format(self.tid))def exitAllThread():    global exitFlag    globalLock.acquire()    exitFlag=1    globalLock.release()workQueue = Queue.Queue() #工作队列globalLock = threading.Lock() #全局变量锁exitFlag = 0 #线程结束
原创粉丝点击