Thread Concurrency: Shared Data, Races and Speedup

When a program must do several things at once, such as serving many clients, filtering a large image, or keeping an interface responsive while it saves a file, it can split the work across threads inside a single process. Threads are cheap to create and communicate through ordinary memory. That shared memory is both their main advantage and their main hazard. This lesson covers what threads share, why unsynchronised updates to shared data go wrong, how a mutex prevents that, and how much speedup extra threads can actually deliver.

Threads share one address space

A thread is an independent flow of execution inside a process. It has its own stack, registers and program counter, and it shares the process's memory and open files with every other thread in that process. On Unix you manage threads with the pthreads library. pthread_create starts a function running in a new thread, and pthread_join makes the caller wait until that thread finishes.


Shared by all threads of the process

Separate for each thread

Global and static variables

Stack, including automatic local variables

Heap memory obtained with malloc

Registers and program counter

Open file descriptors

Thread ID

Program code

Its own copy of errno


Each stack still sits in the shared address space. A thread can therefore reach another thread's local variable if it is handed a pointer to it. Separate means each thread gets its own copy, not that the memory is protected.


If the machine has fewer cores than runnable threads, the threads take turns on the cores. They still run concurrently, but they do not all run in parallel at every instant.

Race conditions and critical sections

For an ordinary non-atomic counter, a useful simplified model of counter++ has three steps: load the value into a register, add 1, and store the result back. This is a teaching model, not a guaranteed machine-instruction sequence. In this model, two threads can load the same old value before either stores its result, losing an increment. A race condition is a bug in which the result depends on the relative timing of threads that access the same data, with at least one of them writing to it.


In C, conflicting accesses from different threads, at least one non-atomic, form a data race when neither happens before the other through synchronisation. Such a data race causes undefined behavior: C imposes no requirements on the result. The timeline illustrates a possible lost update in the simplified model; it does not predict the behavior of a C program containing a data race.


Timeline of two threads each incrementing a shared counter, with Thread A and Thread B steps alternating and the counter value in memory shown after each step.


The lines of code that touch the shared data form a critical section. A mutex, short for mutual exclusion lock, guards it. Only one thread at a time can hold a given mutex. A thread that calls pthread_mutex_lock while another thread holds the lock waits until the lock is released. Protecting every conflicting access with the same mutex orders those accesses and prevents the data race.


C
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;   /* one lock, shared by all threads */
long counter = 0;

void *worker(void *arg) {
    for (int i = 0; i < 1000; i++) {
        pthread_mutex_lock(&lock);
        counter++;                  /* critical section */
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}



How much faster can threads make a program?

Suppose a fraction pp of a program's single-threaded runtime T1T_1 splits evenly across NN threads on NN idle cores, and the rest must stay serial. Amdahl's law gives the speedup:


S(N)=T1TN=1(1−p)+pNS(N) = \frac{T_1}{T_N} = \frac{1}{(1-p) + \dfrac{p}{N}}


As NN grows, p/Np/N shrinks toward zero. For p<1p < 1, the speedup can therefore never exceed 1/(1−p)1/(1-p).


Example: A program spends 90% of its single-threaded time in a loop that splits evenly. With 8 threads, S=1/(0.1+0.9/8)=1/0.2125≈4.71S = 1/(0.1 + 0.9/8) = 1/0.2125 \approx 4.71, not 8. No number of threads can push the speedup past 1/0.1=101/0.1 = 10.



What to remember

  • Threads in one process share globals, heap memory and file descriptors. Each thread has its own stack, registers and program counter.
  • Load–add–store is a simplified model of an ordinary non-atomic increment. Unsynchronised conflicting accesses in C cause a data race and undefined behavior, not merely a predictable lost update.
  • Guard every conflicting access to shared data with the same mutex in every thread.
  • Speedup is limited by the serial fraction: S(N)=1/((1−p)+p/N)S(N) = 1/((1-p) + p/N), which never exceeds 1/(1−p)1/(1-p) when p<1p < 1.

Example: Speeding up an image filter with threads

A single-threaded image filter processes a 1200 × 1000 pixel photo in 72 s. It spends 8 s reading the file, 60 s applying the filter to the pixels, and 4 s writing the result. Only the filtering loop can be split across threads. You split it evenly across 6 threads on a machine with at least 6 idle cores. Each thread also increments a shared counter pixels_done, initially zero, once for every pixel it finishes. For parts a–b, assume ideal parallel execution: ignore thread creation, joining, counting, synchronization and all other overhead. In part d, include only the explicitly specified additional mutex cost.


The speedup of a threaded version is the single-threaded runtime divided by the threaded runtime, S=T1/TNS = T_1 / T_N.


a) Find the runtime with 6 threads and the resulting speedup.


Reading and writing stay serial, so the serial time is 8 s + 4 s = ________.


The 60 s of filtering split six ways takes 60 s / 6 = ________ in each thread, and the six threads run at the same time.


T6=12 s+10 s=22 s,S=T1T6=72 s22 s≈3.27T_6 = 12\ \text{s} + 10\ \text{s} = 22\ \text{s}, \qquad S = \frac{T_1}{T_6} = \frac{72\ \text{s}}{22\ \text{s}} \approx 3.27


Amdahl's law gives the same result. The parallel fraction is p=60/72=5/6p = 60/72 = 5/6, so:


S=1(1−p)+p/6=11/6+5/36=3611≈3.27S = \frac{1}{(1-p)+p/6} = \frac{1}{1/6+5/36} = \frac{36}{11} \approx 3.27


With 6 threads the filter takes 22 s, a speedup of about 3.27, well short of 6.


b) What is the limiting speedup as the number of threads grows without bound?


The serial fraction is 12 s / 72 s, approximately ________. As the number of threads grows, the parallel term p/Np/N shrinks toward zero and only the serial part remains:


Smax⁡=11−p=72 s12 s=6S_{\max} = \frac{1}{1-p} = \frac{72\ \text{s}}{12\ \text{s}} = 6


Even with unlimited cores the runtime cannot fall below its 12 s of serial work. The speedup approaches 6 as the thread count grows, but remains below 6 for any finite thread count in this model.


c) Use a simplified non-atomic load–add–store model for the unprotected counter increments. An illustrative 6-thread run prints pixels_done = 1163488 after all threads finish. How many increments are missing from the reported count, and how can lost updates explain the deficit?


Every pixel should add 1, so the correct final value is 1200 × 1000 = ________.


deficit=1 200 000−1 163 488=36 512\text{deficit} = 1\,200\,000 - 1\,163\,488 = 36\,512


The reported count is short by 36,512 increments, roughly 3.043% of the expected total. In the simplified model, an increment loads the counter, adds one locally and stores the result. When two threads load the same value before either stores, both can store the same result, losing one update. Different interleavings can produce different counts.


This model illustrates one possible outcome; it does not guarantee how pixels_done++ executes. In C with pthreads, concurrent unsynchronized increments of an ordinary shared counter create a data race and undefined behavior. The language therefore does not guarantee merely lost updates or any particular final count.


d) You protect each increment with one shared mutex. A lock, increment and unlock together take 0.25 µs. Because only one thread can hold the mutex, assume these locked sections run one after another, do not overlap filtering and add to the serial time. Find the new speedup, and suggest a better design.


The total locked time is 1,200,000 × 0.25 µs = 300,000 µs = ________.


Adding this to the 22 s runtime from part a gives a new runtime of ________.


S=72 s22.3 s≈3.23S = \frac{72\ \text{s}}{22.3\ \text{s}} \approx 3.23


With every counter access properly synchronized and the final value read after joining the threads, the count is correct. The modeled speedup falls from 3.27 to 3.23. In practice, contention and cache-coherence traffic can add further overhead.


A better design gives each thread a private local counter and adds its local total to pixels_done once, under the mutex, when the thread finishes. This requires only 6 locked updates instead of 1,200,000. Their cost is negligible under the stated assumptions, so the speedup is again about 3.27 while the total stays exact.

Match each term from multithreaded programming on Unix with the description that fits it. Each description is used exactly once.

Match each term
A.

Code region that touches shared data and must not run in two flows of execution at once

B.

Lock object that admits only one holder at a time to the code it guards

C.

Bug whose outcome depends on how concurrent accesses to shared data happen to interleave

D.

Flow of execution with its own stack and registers that shares its process's memory

E.

Bound on speedup set by the fraction of work that must stay serial

F.

Action that completes as one indivisible step and is never observed half done

Atomic operation

Mutex

Critical section

Amdahl's law

Thread

Race condition

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A program sums a large array using four worker threads. Each worker reads a distinct array range and writes its result to its own partial-sum slot. The main thread reports the combined total.


Arrange the stages below so workers can execute in parallel, the reported sum includes every worker's result, and no worker accesses released storage. Treat each listed stage as one complete phase.

Loading ordering steps…

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Two threads belong to the same Unix process and run the same thread function. Which of the following does the second thread share with the first, rather than having its own separate copy? Select all that apply.

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice