0
0
Data-structures-theoryConceptBeginner · 3 min read

FIFO in Queue: What It Means and How It Works

FIFO stands for First In, First Out, which means the first element added to a queue is the first one to be removed. It works like a line where the person who arrives first is served first, ensuring order is maintained.
⚙️

How It Works

A queue is a data structure that follows the FIFO principle, meaning items are processed in the exact order they arrive. Imagine a queue like a line at a grocery store checkout: the first customer to get in line is the first to be served and leave the line.

When you add an item to a queue, it goes to the back of the line. When you remove an item, it comes from the front. This keeps the order fair and predictable, which is useful in many real-life and computing scenarios.

💻

Example

This example shows a simple queue using a list where we add items and remove them in FIFO order.

python
class Queue:
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.append(item)  # Add to the back

    def dequeue(self):
        if not self.is_empty():
            return self.items.pop(0)  # Remove from the front
        return None

    def is_empty(self):
        return len(self.items) == 0

queue = Queue()
queue.enqueue('apple')
queue.enqueue('banana')
queue.enqueue('cherry')

print(queue.dequeue())  # apple
print(queue.dequeue())  # banana
print(queue.dequeue())  # cherry
Output
apple banana cherry
🎯

When to Use

Use FIFO queues when you need to process items in the order they arrive. This is common in situations like:

  • Handling tasks in print queues where documents print in the order sent.
  • Managing requests in web servers to serve users fairly.
  • Simulating real-world lines, like customers waiting for service.

FIFO ensures fairness and predictability, making it ideal for scheduling and buffering tasks.

Key Points

  • FIFO means the first item added is the first removed.
  • Queues follow FIFO to keep order fair and predictable.
  • Useful in many real-world and computing scenarios like task scheduling.
  • Adding items is called enqueue, removing is dequeue.

Key Takeaways

FIFO means the first element added to a queue is the first one removed.
Queues use FIFO to process items in the order they arrive.
Use FIFO queues for fair and predictable task or request handling.
Enqueue adds items to the back; dequeue removes from the front.