Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Queues
Дальше: Wrapping Up

Queues in Action

Queues are common in many applications, ranging from printing jobs to background workers in web applications.

Let’s say we’re programming a simple Python interface for a printer that can accept printing jobs from various computers across a network. We want to make sure we print each document in the order in which it was received.

This code uses our implementation of the Queue class from earlier:

 import​ ​queue
 
 
 class​ PrintManager:
 
 def​ ​__init__​(self):
  self.queue = queue.Queue()
 
 def​ ​queue_print_job​(self, document):
  self.queue.enqueue(document)
 
 def​ ​run​(self):
 while​ self.queue.read():
  self.print_document(self.queue.dequeue())
 
 def​ ​print_document​(self, document):
 # Code to run the actual printer goes here.
 # For demo purposes, we'll print to the terminal:
 print​(document)

We can then utilize this class as follows:

 print_manager = PrintManager()
 print_manager.queue_print_job(​"First Document"​)
 print_manager.queue_print_job(​"Second Document"​)
 print_manager.queue_print_job(​"Third Document"​)
 print_manager.run()

Each time we call queue_print_job, we add the “document” (represented by a string, in this example) to the queue:

 def​ ​queue_print_job​(self, document):
  self.queue.enqueue(document)

When we call run, we print each document by processing it in the order in which it was received. That is, we dequeue each document from the queue and print it:

 def​ ​run​(self):
 while​ self.queue.read():
  self.print_document(self.queue.dequeue())

When we run the previous code, the program will output the three documents in the same order in which they were received:

 First Document
 Second Document
 Third Document

While this example is simplified and abstracts away some of the nitty-gritty details that a real live printing system may have to deal with, the fundamental use of a queue for such an application is very real and serves as the foundation for building such a system.

Queues are also the perfect tool for handling asynchronous requests—they ensure that the requests are processed in the order in which they were received. They’re also commonly used to model real-world scenarios where events need to occur in a certain order, such as airplanes waiting for takeoff and patients waiting for their doctor.

Назад: Queues
Дальше: Wrapping Up