Experiments and implementations · Intermediate

Testing thread cancellation and resource cleanup

Request deferred POSIX thread cancellation and verify cleanup of a held mutex, separating acceptance of the request from completion of thread termination.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Cancellation is a request rather than immediate erasure
  2. Coordinate after registering cleanup
  3. Join before testing the released resource
  4. Unlocking is not a rollback of protected data
  5. Keep unavailable cancellation and external effects in view
  6. Ask Logeia about this articleCheck your understanding

Cancellation is a request rather than immediate erasure

pthread_cancel requests cancellation of another thread. A successful return does not establish that the target has already terminated. Its cancellation state and type determine how the request is acted upon. Use the default deferred type and let a cancellation point receive the request; do not use asynchronous cancellation at an arbitrary instruction. The experiment owns one worker and one mutex and requires a C environment supporting POSIX threads and semaphores on Linux. Calling a cancellation API does not automatically restore every application invariant. The program must explicitly register the cleanup it needs, and the observer must wait for actual termination before interpreting the resource state.

Coordinate after registering cleanup

The worker acquires the mutex, registers an unlock cleanup handler and only then posts a semaphore to tell the main thread it is ready. The main thread waits for that signal before requesting cancellation, making the handler-registration assumption explicit. The worker repeats nanosleep, providing cancellation points for deferred processing. Save the code as cancel.c and compile with cc -std=c11 -O2 -Wall -Wextra -Werror -pthread. Record additional linker requirements if the environment needs them. Check synchronization and thread-creation return values instead of continuing as though initialization succeeded. The semaphore coordinates experiment stages; the mutex remains the resource whose release is being verified after cancellation.

c
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <time.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static sem_t ready;
static void unlock(void *arg) {
    assert(pthread_mutex_unlock(arg) == 0);
}
static void *worker(void *unused) {
    (void)unused;
    assert(pthread_mutex_lock(&lock) == 0);
    pthread_cleanup_push(unlock, &lock);
    assert(sem_post(&ready) == 0);
    for (;;) {
        struct timespec delay = {0, 1000000};
        nanosleep(&delay, NULL);
        pthread_testcancel();
    }
    pthread_cleanup_pop(1);
    return NULL;
}
int main(void) {
    pthread_t thread; void *result;
    assert(sem_init(&ready, 0, 0) == 0);
    assert(pthread_create(&thread, NULL, worker, NULL) == 0);
    int status;
    do { status = sem_wait(&ready); } while (status == -1 && errno == EINTR);
    assert(status == 0);
    assert(pthread_cancel(thread) == 0);
    assert(pthread_join(thread, &result) == 0);
    assert(result == PTHREAD_CANCELED);
    assert(pthread_mutex_trylock(&lock) == 0);
    assert(pthread_mutex_unlock(&lock) == 0);
    assert(pthread_mutex_destroy(&lock) == 0);
    assert(sem_destroy(&ready) == 0);
    puts("canceled thread joined; cleanup released mutex");
    return 0;
}

Join before testing the released resource

The main thread joins the worker and verifies that the returned status is PTHREAD_CANCELED. Only after termination does it try to acquire the mutex. A successful trylock confirms that the held mutex became available along this tested cleanup path. Because the main thread now owns it, the test must unlock it again before destruction. Request acceptance, target termination and resource availability are separate observations. A successful pthread_cancel call alone does not establish the latter two. Keeping the order explicit also avoids testing a resource while the target may still be using it. Final cleanup includes destroying both synchronization objects after their participants have finished.

Unlocking is not a rollback of protected data

An unlock cleanup handler releases the mutex; it does not automatically undo updates made while that mutex was held. Canceling halfway through a two-balance transfer could expose a broken invariant once another thread acquires the lock. A real design may need to group changes, disable cancellation around a critical update, or define precisely which state cleanup restores. This program deliberately changes no protected business data, isolating the resource-release property. Before transplanting the same handler into a larger operation, enumerate possible cancellation positions and the states visible afterward. A resource can be successfully released while the application state remains incorrect, so both aspects require separate reasoning.

Keep unavailable cancellation and external effects in view

A target that disables cancellation or never reaches the expected cancellation point may not terminate promptly after a request. Give the experiment an outer finite runtime bound. Production work can also own sockets, files, buffers and completion records beyond a mutex. Terminating a thread does not retract an email already sent or a database change already committed. Define who ultimately releases each resource and how an uncertain result is reported to the caller. The observed result here applies to this deferred-cancellation and cleanup-handler path only. It is not a guarantee that arbitrary cancellation is safe or that the same cleanup action is sufficient for every operation holding a lock.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 18

Understand the systems behind the web · STEP 15

Choose a learning path