Technical skill

Linux mutex P-threads

Why two workers can lose one update

Imagine two people keeping the same job counter. Both look at the number 4, each adds one, and each writes 5. The counter should be 6, but one update disappeared. A program can make the same mistake when two threads change shared memory at the same time.

A process is a running program. It can have several threads, which are separate paths of execution inside that program. Threads in one process share memory and open file descriptors, small numbers used to refer to files or devices that are already open. Each thread keeps its own execution state and stack, a private memory area used for function calls. Shared memory lets threads pass data quickly, but they need rules for changing the same value. A mutex is a lock: one thread holds it while it works with protected data. The short section of code inside that lock is called a critical section.

For example, a completed-job count should equal the number of jobs workers have finished. That relationship is an invariant, a condition the program must keep true. In a POSIX threads program, or Pthreads program, a mutex can protect the shared count. Initialize it before worker threads start:

static pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned completed;

Every read or update that depends on the same rule must use the same mutex. This update locks the counter while it changes:

pthread_mutex_lock(&count_lock);
++completed;
pthread_mutex_unlock(&count_lock);

Pthread functions usually return an error number directly and leave errno unchanged. Check the return from each lock operation. If locking fails, the thread does not own the mutex and should not proceed as though it does. Keep the locked section brief: read or update shared values, then unlock before file or network work. Lock related fields together when they form one invariant.

Make ownership and order clear

The thread that locks a normal mutex owns it until it unlocks it. Another thread must not unlock it, and the program must not destroy the mutex while a thread could still use or wait for it. Stop or join worker threads before destroying the mutex or freeing the data it protects. Early returns can accidentally leave a lock held, so collect a result inside the protected section, unlock, and only then return. Every code path that reads or writes protected data must follow the same rule.

Deadlock happens when threads wait on locks in a cycle. If a task needs two mutexes, use the same lock order everywhere and release them in reverse order. Avoid calling unknown callbacks while holding a lock, since a callback may wait on another lock or block.

pthread_mutex_trylock() returns immediately when a mutex is busy. A tight retry loop wastes CPU without fixing the design. If a thread should sleep until a condition becomes true, use a condition variable with the mutex: check the condition in a loop, then wait. Waiting releases the mutex while the thread sleeps and locks it again before returning. An atomic operation may suit a simple counter if it preserves the program's rule. Use process-shared mutex attributes only when separate processes share the mutex in shared memory; threads in one process normally use the simpler process-private mutex. A review can list shared variables, their locks, and who uses them.

Interactive exercises

Materials

Skillsets
Skillset Devops preview
image descriptionDevops
by Ajay Kumar
2004 users
Skillset Linux administrator preview
image descriptionLinux administrator
by Infinite Education
3080 users
Skillset Linux for backend developer preview
image descriptionLinux for backend developer
by Artem Naumenko (fb)
16 users
Skillset Devops preview
image descriptionDevops
by Dio
3 users
Do you know that ...?
Any useful or interesting facts about the skill. Any peace of information would be useful