deque and LifoQueue
In the previous lesson, I showed you how to use Python’s built-in
list as a stack. In this lesson, I will show you how to use the double-ended queue and LIFO queue structures instead. Inside of the
collections library, you will find a double-ended queue called
A double-ended queue is one that supports adding and removing items from either end. Because of this, it can be used either as a stack or a queue. Underneath the covers,
deque is implemented as a doubly-linked list.
Just like a list, the
.pop() method takes the top item off and returns it. There’s a companion to
.popleft() and it does what
.pop() does but from the other end of the queue. Again, not strictly a stack operation.
01:46 Whenever you have multiple threads in a system, there’s a danger of race conditions. At any time, the operating system may decide to stop paying attention to the current thread and schedule a different one. If you’re sharing state between threads, bad things can happen. To resolve this kind of problem, your code needs to be able to declare a section atomic.
It can do this with a lock. The
LifoQueue class found in the
queue library is a thread-safe stack. It guarantees that operations on it are atomic and won’t be mangled by the operating system context switching to another thread.
Consider a program with two threads and a shared
LifoQueue object between them. First, I’ll start off with the familiar eating action and then Thread 1 will push it onto the
LifoQueue using the
If Thread 2 makes another call to
.get(), it blocks as there’s nothing in the stack to pop off. Meanwhile, back in Thread 1—you remember Thread 1, right? It was so long ago—I’ll take the next step, and
.put() pushes it onto the stack.
This allows the thread to check if there’s something in the queue for it, but keeps doing other things if there isn’t anything waiting for it. Let’s open up the REPL and take a look at
LifoQueue. First off, I’ll import it from the
queue library, then instantiate it.
And then one more time, and I get the exception. The
Empty exception is raised because there was nothing in the queue. That’s all for using queues as stacks. Next up, I’ll talk about the pros and cons of the different ways of getting stack-like behavior in Python.
Become a Member to join the conversation.