แนะนำตัว...
โมดูลคิวมีโครงสร้างข้อมูลเข้าก่อน ออกก่อน (FIFO) เข้าก่อนออกก่อน (LIFO) ที่เหมาะสำหรับการเขียนโปรแกรมแบบมัลติเธรด สามารถใช้คิวเพื่อส่งข้อมูลหรือข้อมูลต่างๆ ได้หลากหลายเช่น รายละเอียดเซสชัน เส้นทาง ตัวแปร .. ระหว่างผู้สร้างและผู้ใช้เธรดอย่างปลอดภัย โดยทั่วไปการล็อคจะได้รับการจัดการสำหรับผู้โทร
หมายเหตุ :การสนทนานี้ถือว่าคุณเข้าใจลักษณะทั่วไปของคิวแล้ว หากไม่อ่าน คุณอาจต้องการอ่านข้อมูลอ้างอิงบางส่วนก่อนดำเนินการต่อ
1. ให้เราใช้คิว FIFO พื้นฐาน
import queue
fifo = queue.Queue()
# put numbers into queue
for i in range(5):
fifo.put(i)
# if not empty get the numbers from queue
print(f"Ouput \n")
while not fifo.empty():
print(f" {fifo.get()} ") ผลลัพธ์
0 1 2 3 4
2. ตัวอย่างข้างต้นใช้เธรดเดียวเพื่อแสดงว่าองค์ประกอบจะถูกลบออกจากคิวในลำดับเดียวกันกับที่แทรกเข้าไป
3. ให้เราใช้คิว LIFO พื้นฐาน
import queue
lifo = queue.LifoQueue()
# put numbers into queue
for i in range(5):
lifo.put(i)
print(f"Ouput \n")
# if not empty get the numbers from queue
while not lifo.empty():
print(f" {lifo.get()} ") ผลลัพธ์
4 3 2 1 0
4. ตัวอย่างข้างต้นแสดงให้เห็นว่าการใส่ลงในคิวล่าสุดถูกลบโดย get
5. สุดท้าย มาดูวิธีการใช้ Priority Queue
บางครั้ง ลำดับการประมวลผลของรายการในคิวจำเป็นต้องยึดตามลำดับความสำคัญของรายการเหล่านั้น มากกว่าแค่ลำดับที่สร้างหรือเพิ่มลงในคิว ตัวอย่างเช่น งานสำคัญทางธุรกิจที่ทำงานใน Producton ต้องการ CPU สูงสุดและมีความสำคัญเหนืองานพิมพ์ที่นักพัฒนาต้องการพิมพ์ PriorityQueue ใช้การเรียงลำดับเนื้อหาของคิวเพื่อตัดสินใจว่าจะดึงไอเท็มใด
import queue
import threading
# Class to get the priority and description and validate the priority
class Job:
def __init__(self, priority, description):
self.priority = priority
self.description = description
print('New job:', description)
return
def __eq__(self, other):
try:
return self.priority == other.priority
except AttributeError:
return NotImplemented
def __lt__(self, other):
try:
return self.priority < other.priority
except AttributeError:
return NotImplemented
# create a priority queue and define the priority
q = queue.PriorityQueue()
q.put(Job(90, 'Developer-Print job'))
q.put(Job(2, 'Business-Report job'))
q.put(Job(1, 'Business-Critical Job'))
# process the job
def process_job(q):
while True:
next_job = q.get()
print(f" *** Now, Processing the job - {next_job.description}")
q.task_done()
# define the threads
workers = [
threading.Thread(target=process_job, args=(q,)),
threading.Thread(target=process_job, args=(q,)), ]
# call the threads and join them.
for w in workers:
w.setDaemon(True)
w.start()
q.join() ผลลัพธ์
job: Developer-Print job New job: Business-Report job New job: Business-Critical Job
ผลลัพธ์
*** Now, Processing the job - Business-Critical Job *** Now, Processing the job - Business-Report job *** Now, Processing the job - Developer-Print job
6. ตัวอย่างนี้มีหลายเธรดที่ใช้งานซึ่งได้รับการประมวลผลตามลำดับความสำคัญของรายการในคิว ณ เวลาที่เรียก get() ลำดับของการประมวลผลขึ้นอยู่กับความสำคัญของธุรกิจโดยไม่คำนึงถึงลำดับที่เพิ่มเข้ามา