Threads with pthreads

Splitting a matrix multiply across CPU threads — why one thread per element crashes, and how a handful of threads with a block of rows each gets a real speedup.

What you'll learn
  • Create and join POSIX threads and pass each one its own arguments
  • Choose a work split with no shared writes, so no locks are needed
  • Estimate when thread overhead and memory bandwidth cap the speedup

A matrix product \(C = AB\) is easy to parallelise: every element \(C_{ij} = \sum_k A_{ik} B_{kj}\) is independent of every other. The repository’s program takes that literally and gives each element its own thread:

#define N 1000
pthread_t threads[N][N];
Args args[N][N];

for (int i = 0; i < N; i++)
    for (int j = 0; j < N; j++) {
        args[i][j].row = i;
        args[i][j].col = j;
        pthread_create(&threads[i][j], NULL, thread_worker, &args[i][j]);
    }

Each thread gets a pointer to its own Args, which is right: passing the address of one shared loop variable would let threads read each other’s coordinates.

Filling the output matrix. As written, the main thread creates one thread per element, one after another. Switch to row blocks: T threads each own a band of rows and work at the same time.

Why it crashes

The program never gets as far as creating a thread. threads and args are local arrays of a million 8-byte entries each: 16 MB on the stack, which is 8 MB by default on Linux. A test program declaring just those two arrays segfaults immediately, and runs once the stack limit is raised with ulimit -s 32768. (The matrices themselves are globals, so they live in the zero-filled .bss segment and are fine.)

With a larger stack it would still be a bad plan. Creating and joining one thread costs about 100 µs here, so a million threads spend about 100 s on overhead — to do arithmetic that takes 0.44 s on a single thread. The system’s thread limit (/proc/sys/kernel/threads-max, 125,846 on this machine) would also stop pthread_create long before the millionth thread, and the program never checks its return value.

A handful of threads, a block of rows each

The fix is to make the work per thread large. With T threads, thread t takes rows t*N/T up to (t+1)*N/T:

void *work(void *arg) {
    long t = (long)arg;
    int r0 = t * N / T, r1 = (t + 1) * N / T;
    for (int i = r0; i < r1; i++)
        for (int j = 0; j < N; j++) {
            int s = 0;
            for (int k = 0; k < N; k++) s += A[i][k] * B[k][j];
            C[i][j] = s;
        }
    return NULL;
}

No two threads write the same element, so no mutex is needed, and the result matches the single-threaded checksum exactly.

Measured speedup of the row-block version. Two threads double the speed; beyond about eight, adding threads gains little because the inner loop reads B column by column and memory, not arithmetic, becomes the limit.

The flattening is a memory effect. B[k][j] with k varying jumps 4,000 bytes between reads, so most of them miss the cache. Swapping the two inner loops — for k, then for j, accumulating into C[i][j] — reads B row by row and halves the single-threaded time here, from 0.44 s to 0.22 s, before any threads are added.

The same product on a GPU

matrix_mul.c in the same folder is the GPU version: a CUDA kernel that gives each GPU thread one element, which is exactly the right granularity there, where threads cost almost nothing to start. It uses __global__ and the <<<grid, block>>> launch syntax, so it must be saved as .cu and compiled with nvcc; gcc rejects it. The CUDA course builds this kernel step by step, including the shared-memory tiling that fixes the same column-access problem.

Try it yourself. Build the row-block version with gcc -O2 mm.c -lpthread, time it for T = 1, 2, 4 and the output of nproc, and plot your own speedup curve. Then swap the inner loops and time it again. Finally, check the original program’s failure yourself with ulimit -s and a test file that declares only the two arrays.

View source on GitHub →