Concurrent Queues
This lesson presents the design and implementation of a thread-safe queue.
As you know by now, there is always a standard method to make a concurrent data structure: add a big lock. For a queue, let’s skip that approach, assuming you can figure it out.
Instead, let’s take a look at
typedef struct __node_t {int value;struct __node_t *next;} node_t;typedef struct __queue_t {node_t *head;node_t *tail;pthread_mutex_t head_lock, tail_lock;}void Queue_Init(queue_t *q) {node_t *tmp = malloc(sizeof(node_t));tmp->next = NULL;q->head = q->tail = tmp;pthread_mutex_init(&q->head_lock, NULL);pthread_mutex_init(&q->tail_lock, NULL);}void Queue_Enqueue(queue_t *q, int value) {node_t *tmp = malloc(sizeof(node_t));assert(tmp != NULL);tmp->value = value;tmp->next = NULL;pthread_mutex_lock(&q->tail_lock);q->tail->next = tmp;q->tail = tmp;pthread_mutex_unlock(&q->tail_lock);}int Queue_Dequeue(queue_t *q, int *value) {pthread_mutex_lock(&q->head_lock);node_t *tmp = q->head;node_t *new_head = tmp->next;if (new_head == NULL) {pthread_mutex_unlock(&q->head_lock);return -1; // queue was empty}*value = new_head->value;q->head = new_head;pthread_mutex_unlock(&q->head_lock);free(tmp);return 0;}
If you study this code carefully, you’ll notice that there are two locks, one for the head of the queue, and one for the tail. The goal of these two locks is to enable concurrency of enqueue and dequeue operations. In the common case, the enqueue routine will only access the tail lock, and dequeue only the head lock.
One trick used by Michael and Scott is to add a dummy node (allocated in the queue initialization code); this dummy enables the separation of head and tail operations. Study the code, or better yet, copy it, run it locally, and measure it, to understand how it works deeply.
Queues are commonly used in multi-threaded applications. However, the type of queue used here, with just locks, often does not completely meet the needs of such programs. A more fully developed bounded queue, that enables a thread to wait if the queue is either empty or overly full, is the subject of our intense study in the next chapter on condition variables. Watch for it!
Get hands-on with 1400+ tech skills courses.