Data Structures and Concurrency

Article · 3:00

Linked lists, stacks, queues and hash tables built from malloc and a pointer - then threads.

This is the capstone, and the reason the earlier phases were in that order. C gives you no containers, so you build them, and building them is what makes pointers permanent knowledge rather than a topic you read.

A linked list is a node holding a value and a pointer to the next node. Insertion at the head is constant time; finding the nth element is linear. The operation that teaches the most is deletion, because it requires the previous node - which is why a pointer-to-pointer walk, keeping the address of the link rather than the node, removes the special case for the head entirely.

A stack is last-in first-out, and is either a growable array or a list with push and pop at the head. A queue is first-in first-out, and needs pointers to both ends or the dequeue is linear. A hash table maps a key to a bucket with a hash function and resolves collisions, usually with a list per bucket; a good hash spreads keys evenly, and a bad one turns the table into one long list.

POSIX threads are the introduction to concurrency. pthread_create starts a thread, pthread_join waits for it, and a pthread_mutex_t protects anything two threads touch. The whole of the difficulty is that an unprotected shared variable is a data race, and count++ is three operations - read, add, write - that can interleave. Compile with -pthread and test under -fsanitize=thread.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

typedef struct Node { int value; struct Node *next; } Node;

/* Insert at the head: constant time, and the ** means the caller's
   pointer is updated rather than a copy of it. */
int push_front(Node **head, int value)
{
    Node *n = malloc(sizeof *n);
    if (!n) return -1;
    n->value = value;
    n->next  = *head;
    *head    = n;
    return 0;
}

/* The pointer-to-pointer walk. By holding the address of the LINK
   rather than the node, removing the head needs no special case -
   which is the trick worth learning from this whole phase. */
void remove_value(Node **head, int value)
{
    for (Node **link = head; *link != NULL; link = &(*link)->next) {
        if ((*link)->value == value) {
            Node *dead = *link;
            *link = dead->next;
            free(dead);
            return;
        }
    }
}

void destroy(Node *head)
{
    while (head) { Node *next = head->next; free(head); head = next; }
}

/* Threads: count++ is read, add, write - three steps that interleave. */
static long counter = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void *worker(void *arg)
{
    (void) arg;
    for (int i = 0; i < 100000; i++) {
        pthread_mutex_lock(&lock);
        counter++;                       /* without the lock: a data race */
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main(void)
{
    Node *list = NULL;
    push_front(&list, 3); push_front(&list, 2); push_front(&list, 1);
    remove_value(&list, 2);
    for (Node *it = list; it; it = it->next) printf("%d ", it->value);
    printf("\n");
    destroy(list);

    pthread_t a, b;
    pthread_create(&a, NULL, worker, NULL);
    pthread_create(&b, NULL, worker, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("counter = %ld\n", counter);    /* 200000, with the lock */

    /* gcc -Wall -Wextra -pthread main.c -o main
       gcc -fsanitize=thread -g -pthread main.c -o main   # finds races */
    return 0;
}

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course What each phase is for, the four projects to build alongside it, and the compiler flags that turn C from dangerous into merely strict. 3 min read