Thread-safe task queue on a linked list
A task queue was written for one thread: a singly linked list with head and tail, where put appends at the tail and get removes from the head. Explain what goes wrong when many producer and consumer threads share it, then make it safe:
-
put(value, timeout=None)blocks while the queue is atcapacity(if one is set) and raisesFullon timeout. -
get(timeout=None)blocks while the queue is empty and raisesEmptyon timeout. -
close()makes laterputcalls raiseClosed; consumers drain what is left, thengetraisesClosed. Waiting threads must wake up. - Every task is delivered exactly once; one producer's tasks come out in the order it put them.
class Empty(Exception): ...
class Full(Exception): ...
class Closed(Exception): ...
class TaskQueue:
def __init__(self, capacity=None): ...
def put(self, value, timeout=None): ...
def get(self, timeout=None): ...
def close(self): ...
def __len__(self): ...
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
