💻 Programming

Queue

Queue

A FIFO (first-in, first-out) data structure. Used for task scheduling and BFS. The foundational concept of message queues.

📖 Detailed Explanation

A queue is a data structure that follows the FIFO (First In, First Out) principle. Data that enters first leaves first, working in the same way as waiting in line. It provides two core operations: enqueue (insertion) and dequeue (removal).

Queues are used in a wide variety of places. They are essential in operating system process scheduling, printer job queues, network packet processing, and the BFS (breadth-first search) algorithm for graphs. In web development, they are also the underlying concept of job queues and message queue systems.

Variants of the queue include the deque (double-ended queue), the priority queue, and the circular queue. A priority queue removes elements according to priority rather than insertion order, and is implemented with a heap. A deque allows both insertion and deletion at either end.

In distributed systems, message queues (RabbitMQ, Apache Kafka, Amazon SQS, etc.) are central to asynchronous communication between services. In this pattern, a producer puts messages into the queue and a consumer processes them, which lowers coupling between services and increases scalability.

💻 Code Example

# Python 큐 구현 및 활용

from collections import deque
import queue

# 1. deque로 큐 구현 (권장)
q = deque()
q.append(1)      # enqueue
q.append(2)
q.append(3)
first = q.popleft()  # dequeue -> 1
print(list(q))   # [2, 3]

# 2. queue.Queue (스레드 안전)
thread_safe_q = queue.Queue()
thread_safe_q.put('task1')
thread_safe_q.put('task2')
task = thread_safe_q.get()  # 'task1'

# 3. 우선순위 큐
import heapq
pq = []
heapq.heappush(pq, (2, 'medium'))
heapq.heappush(pq, (1, 'high'))
heapq.heappush(pq, (3, 'low'))
print(heapq.heappop(pq))  # (1, 'high')

# 4. BFS에서 큐 활용
def bfs(graph, start):
    visited = set()
    queue = deque([start])
    result = []

    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.add(node)
            result.append(node)
            queue.extend(graph[node])

    return result

# 그래프 예시
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [], 'E': [], 'F': []
}
print(bfs(graph, 'A'))  # ['A', 'B', 'C', 'D', 'E', 'F']

🗣️ Examples of Practical Conversations

Senior: Email sending is synchronous, so responses are slow. Let's separate it out with a message queue.

Junior: Which queue system should we use?

Senior: Since the scale is small, let's start with Redis Queue and move to RabbitMQ later if needed. First, we should separate email sending so that a worker handles it.

Interviewer: Please explain the difference between a stack and a queue.

Candidate: A stack is LIFO, so the last item in is the first out, while a queue is FIFO, so the first item in is the first out. Stacks are used for function calls and undo, and queues are used for job scheduling and BFS traversal.

Interviewer: Why do you use a queue in BFS?

Candidate: Because nodes at the same level must be visited first. If you put adjacent nodes into the queue and take them out in order, the traversal naturally proceeds in level order.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer: You implemented the queue with a list, but pop(0) is O(n).

Author: Since there's little data, wouldn't it be fine?

Reviewer: If you use a deque, popleft() is O(1). It's good to make a habit of choosing efficient data structures.

⚠️ Cautions

🔗 Related Terms

📚 Learn More