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

目标

开始学习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-8

import threading
import time
import traceback
import os

import Queue

class 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 #线程结束

你可能感兴趣的:(Python)