Little thoughts on mutex & queue

microwavestine
2 min readJul 25, 2022

--

ELI5 Why does mutex look like a queue?

There were two modules in a NestJS project at work that used async-mutex, which, as the name implies, is a npm mutex library, and Nest-JS wrapped bull JS, which is a queuing library that uses Redis.

At a glance those two seemed to essentially solve the same problem of queuing requests, so I wondered what their differences were.

Mutex’s goal is to prevent race condition

In computer science, mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions.

The problem which mutual exclusion addresses is a problem of resource sharing: how can a software system control multiple processes’ access to a shared resource, when each process needs exclusive control of that resource while doing its work?

Queue is an abstract data type

In computer science, a queue is a collection of entities that are maintained in a sequence

Queue, on the other hand, was not designed to solve a particular problem.

Queues provide services in computer science, transport, and operations research where various entities such as data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs the function of a buffer. Another usage of queues is in the implementation of breadth-first search.

Queue lines up a series of jobs or tasks to be performed and executes them. The order often does not matter, so long as they are executed.

Conclusion

A structure in the form of a queue appears when processes line up according to mutex rule. Users would line up for access to a resource.

The queue, as implemented by BullJS, is an abstraction of that structure. It lines things up to be done asynchronously in the background, but does not guarantee order or immediate processing.

--

--