python 线程中可比较对象在优先队列的使用
1 from queue import PriorityQueue 2 import time 3 import random 4 import threading 5 6 7 class CompareAble: 8 # 定义一个可比较对象 9 def __init__(self, priority, job_name): 10 self.priority = priority 11 self.jobname = job_name 12 13 def __lt__(self, other): 14 if self.priority > other.priority: 15 return False 16 else: 17 return True 18 19 20 tasks = [(i, "do task %s" % i) for i in range(10, 100, 5)] 21 22 23 def produce(pq, lock): 24 while True: 25 lock.acquire() 26 task = tasks[random.randint(0, len(tasks)-1)] 27 print('put %s %s in pq' % (task[0], task[1])) 28 pq.put(CompareAble(task[0], task[1])) 29 lock.release() 30 time.sleep(1) 31 32 33 def consumer(pq, lock): 34 while True: 35 lock.acquire() 36 try: 37 if pq.empty(): 38 continue 39 task = pq.get_nowait() 40 if task: 41 print(task.priority, task.jobname) 42 finally: 43 lock.release() 44 time.sleep(1) 45 46 47 if __name__ == '__main__': 48 task_queue = PriorityQueue() 49 task_lock = threading.Lock() 50 for i in range(3): 51 t = threading.Thread(target=produce, args=(task_queue, task_lock)) 52 t.setDaemon(True) # 设置为守护进程 53 t.start() 54 for i in range(2): 55 t = threading.Thread(target=consumer, args=(task_queue, task_lock)) 56 t.setDaemon(True) 57 t.start() 58 time.sleep(30) 59 print("over")
t.setDaemon(True) 主线程退出,子线程t也跟着退出
可比较对象中 def __lt__(self, other): 返回True的优先被get出来