Queues in Action

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

Let’s say you were programming a simple Ruby interface for a printer that can accept printing jobs from various computers across a network. By utilizing the Ruby array’s push method, which adds data to the end of the array, and the shift method, which removes data from the beginning of the array, you may create a class like this:

 class​ PrintManager
 
 def​ ​initialize
  @queue = []
 end
 
 def​ ​queue_print_job​(document)
  @queue.​push​(document)
 end
 
 def​ ​run
 while​ @queue.​any?
 # the Ruby shift method removes and returns the
 # first element of an array:
  print(@queue.​shift​)
 end
 end
 
 private
 
 def​ ​print​(document)
 # Code to run the actual printer goes here.
 # For demo purposes, we'll print to the terminal:
  puts document
 end
 
 end

We can then utilize this class as follows:

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

The printer will then print 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 are 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset