Sobes.tech
Junior — Middle

Could you give an example of a situation where using a queue is justified in practice?

sobes.tech AI

Answer from AI

A queue is a data structure that operates on the FIFO (First In, First Out) principle. A practical example of using a queue:

Task processing in a multithreaded application:

Suppose you have a server that receives requests from users. To avoid blocking the main thread, requests are placed in a task queue. Separate worker threads take tasks from the queue and process them in order.

Example in Python using queue.Queue:

import queue
import threading
import time

# Create a queue
task_queue = queue.Queue()

# Task handler function
def worker():
    while True:
        task = task_queue.get()
        if task is None:  # signal to terminate
            break
        print(f"Processing task: {task}")
        time.sleep(1)  # simulate work
        task_queue.task_done()

# Start worker thread
thread = threading.Thread(target=worker)
thread.start()

# Add tasks
for i in range(5):
    task_queue.put(f"Task {i}")

# Wait for all tasks to be processed
task_queue.join()

# Stop the thread
task_queue.put(None)
thread.join()

Thus, a queue helps organize ordered and safe task transfer between threads.

Could you give an example of a situation where using… - sobes.tech