Python provides multi-producer, multi-consumer, thread safe queues. These queues are available in standard libraries so you can use them without installing any other library.
For Python 3 you have to import queue while for Python 2.7 you have to import Queue, anyway the code for this post has been tested only on python 3.



The imported modules implements three types of queue, which differ only in the order in which the entries are retrieved.
The three types are:

  • FIFO queues
  • LIFO queues
  • Priority queues

FIFO stands for first in first out, that means the first item arrived is the first item retrieved. For examplem, this type of queue can be used to model a queue to pay at the supermarket.
LIFO stands for Last in First out. This type of queue can be used to model a set of physical items stacked on top of each other, which makes it easy to take an item off the top of the stack, for example a stack of dishes.
Priority queue is a special kind of queue, this queue is used to insure that more important items are handled before less important ones. For example in the emergency room the most serious patients are treated before the less serious ones, while patients with the same urgency are handled as in a FIFO queue.

In this post I’m going to explain FIFO and LIFO queue in python 3, I’ll explain Priority queues in another post.

Let’s start:
To explain FIFO and LIFO queues I’m going to implement a simple multithreaded producer-consumer program.

A thread will produce (push) items in the queue and a thread will retrieve (pop) items from the queue.
The producer thread will push an item in the queue every “timing” seconds for 20 times:


The consumer thread will pop an item from the queue every “timing” seconds for 20 times, this thread prints out the element popped and current content of the queue:

to invoke start the threads:

and to work in LIFO mode you have only to change the line


The output will show the FIFO and LIFO working.
You can find full source code for this post on my github: FIFO and LIFO queues in python