Python priority queue implementation method example, python priority queue example
This article describes how to implement the Python priority queue. We will share this with you for your reference. The details are as follows:
1. Code
Import Queueimport threadingclass Job (object): def _ init _ (self, priority, description): self. priority = priority self. description = description print 'new job: ', description return def _ cmp _ (self, other): return cmp (self. priority, other. priority) q = Queue. priorityQueue () q. put (Job (3, 'mid-level job') q. put (Job (10, 'low-level job') q. put (Job (1, 'impant ant job') def process_job (q): while True: next_job = q. get () print 'processing job: ', next_job.description q. task_done () workers = [threading. thread (target = process_job, args = (q,), threading. thread (target = process_job, args = (q,),] for w in workers: w. setDaemon (True) w. start () q. join ()
2. Execution result
New job: Mid-level jobNew job: Low-level jobNew job: Important jobProcessing job: Mid-level jobProcessing job: Low-level job