queue in python module code example
Example 1: python threading queue
import threading, queue
q = queue.Queue()
def worker():
while True:
item = q.get()
print(f'Working on {item}')
print(f'Finished {item}')
q.task_done()
threading.Thread(target=worker, daemon=True).start()
for item in range(30):
q.put(item)
print('All task requests sent\n', end='')
q.join()
print('All work completed')
Example 2: python queue.priority queue
from queue import PriorityQueue
class PqElement(object):
def __init__(self, value: int):
self.val = value
def __lt__(self, other):
"""self < obj."""
return self.val > other.val
def __repr__(self):
return f'PQE:{self.val}'
pq = PriorityQueue()
pq.put(PqElement(v))
topValue = pq.get()
topValue = pq.queue[0].val