Aller au contenu

Threads en programmation concurrente

Cette section contient des exemples d'utilisation des threads pour la programmation concurrente en C. Voici la liste des fichiers sources, avec un lien vers leur contenu.

Fichier Description Lien
test_pthread.c Crée puis joint 50 000 threads l'un après l'autre et mesure le temps écoulé avec clock_gettime() ; comparer avec test_fork.c Voir
test_fork.c Même mesure avec des processus : crée et attend 50 000 enfants avec fork() / waitpid(), pour comparer le coût d'un processus à celui d'un thread (test_pthread.c) Voir
knowing_nbcores.c Obtient le nombre de processeurs en ligne avec sysconf(_SC_NPROCESSORS_ONLN) Voir
thread_01.c Le thread A écrit une variable globale pendant que le thread B la lit, sans synchronisation (situation de compétition volontaire) Voir
thread_02.c Trois threads qui affichent des lettres : main crée A et B, B crée C et l'attend avec pthread_join() ; les sorties des threads s'entremêlent Voir
thread_02_withmutex.c Identique à thread_02.c, mais chaque bloc de lettres est affiché sous la protection d'un pthread_mutex_t, si bien que les blocs ne s'entremêlent plus Voir
thread_with_shm_without_mutex.c 4 producteurs et 1 consommateur accèdent à une variable globale (partagée par les threads) sans mutex : situation de compétition sur les données Voir
thread_with_shm_and_mutex.c 4 producteurs et 1 consommateur partagent une variable protégée par un mutex (scrutation active) ; le consommateur s'arrête quand les producteurs ont terminé Voir
thread_with_conditions.c Trois threads incrémentent un compteur ; quand il atteint une limite, l'un d'eux réveille avec pthread_cond_signal() un thread de surveillance, qui attend avec pthread_cond_wait() (adapté du LLNL) Voir
thread_with_signal.c Signal et threads : main() envoie SIGINT à un thread avec pthread_kill() ; le gestionnaire, async-signal-safe, positionne un indicateur qui arrête le thread Voir
pb_reentrant.c Montre le problème d'une fonction non réentrante à état static caché (comme rand()) appelée depuis 4 threads : ils affichent 4 valeurs différentes ; comparer avec without_pb_reentrant.c (16838 quatre fois) Voir
without_pb_reentrant.c Correction de pb_reentrant.c : version réentrante où l'appelant fournit l'état (comme rand_r()) Voir
pthread_barrier.c Implémentation maison de pthread_barrier_t pour macOS, qui ne la fournit pas nativement Voir
barrier.c Illustre pthread_barrier_wait() : tous les threads se bloquent jusqu'à l'arrivée du dernier Voir
timer_and_citizens.c Un thread minuteur réveille des threads citoyens avec pthread_cond_broadcast() (prédicat + boucle while) Voir
thread_hello.c Premier programme Pthread : crée un thread, affiche les deux identifiants avec pthread_self(), puis le joint (cours, chapitre "Threads") Voir
thread_square.c Passe un argument à un thread et récupère son résultat (alloué sur le tas) avec pthread_join() (cours, chapitre "Threads") Voir
thread_detached.c Crée un thread détaché avec PTHREAD_CREATE_DETACHED ; main() se termine par pthread_exit() (cours, chapitre "Threads") Voir
matrix_product_threads.c Exemple fil rouge : produit de matrices carrées calculé par 4 threads, un par quadrant du résultat, comparé à la version à un seul thread (cours, chapitre "Threads") Voir
thread_shared_variables.c Programme à analyser : quelles variables (globales, static, locales, via un pointeur) sont partagées par les threads (cours, chapitre "Threads") Voir
thread_arg_pitfall.c Piège du passage de &i d'une boucle à plusieurs threads, suivi de la correction (un argument par thread) (cours, chapitre "Threads") Voir

Code source

include/pthread_barrier.h

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef PTHREAD_BARRIER_H
#define PTHREAD_BARRIER_H

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

#define PTHREAD_BARRIER_SERIAL_THREAD 1

typedef struct {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    unsigned count;          /* number of threads to wait for */
    unsigned waiting;        /* number of threads already arrived */
    unsigned generation;     /* incremented each time the barrier opens */
} pthread_barrier_t;

int pthread_barrier_init(pthread_barrier_t *barrier, const void *attr, unsigned count);

int pthread_barrier_wait(pthread_barrier_t *barrier);

int pthread_barrier_destroy(pthread_barrier_t *barrier);

#endif
src/barrier.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>

#ifdef __APPLE__
#include "pthread_barrier.h"
#endif

#ifndef THREAD_COUNT
#define THREAD_COUNT 5
#endif

/**
 * @file barrier.c
 * @brief Demonstrates the use of pthread_barrier for thread synchronization.
 *
 * This program creates a number of threads defined by THREAD_COUNT, each waiting
 * for a random period before reaching a synchronization point, implemented using
 * a pthread_barrier. Once all threads have reached this point, they continue their
 * execution.
 *
 * rand() is not thread-safe: each thread uses rand_r() with its own seed.
 * macOS does not provide pthread_barrier_t: pthread_barrier.c is linked
 * there instead.
 *
 * Usage:
 *     Compile with -pthread flag (gcc -pthread barrier.c)
 *     Run the executable
 */

pthread_barrier_t barrier;

void *doit(void *arg) {
    int tid = *(int *) arg;
    unsigned int seed = (unsigned int) time(NULL) + tid;  /* private */
    int wait_sec = 1 + rand_r(&seed) % 5;

    printf("thread %d: wait for %d seconds.\n", tid, wait_sec);
    sleep(wait_sec);
    printf("thread %d: Ready...\n", tid);

    pthread_barrier_wait(&barrier);

    printf("thread %d: passed the barrier!\n", tid);

    free(arg);  /* Free the dynamically allocated memory */
    return NULL;
}

int main(void) {
    pthread_t tid[THREAD_COUNT];
    int i, err;

    err = pthread_barrier_init(&barrier, NULL, THREAD_COUNT + 1);
    if (err != 0) {
        fprintf(stderr, "pthread_barrier_init: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }

    for (i = 0; i < THREAD_COUNT; i++) {
        int *arg = malloc(sizeof(int));  /* Dynamically allocate memory for thread ID */
        if (arg == NULL) {
            perror("Failed to allocate memory for thread ID");
            exit(EXIT_FAILURE);
        }
        *arg = i;
        err = pthread_create(&tid[i], NULL, doit, arg);
        if (err != 0) {
            fprintf(stderr, "pthread_create: %s\n", strerror(err));
            free(arg);  /* Free the allocated memory in case of failure */
            exit(EXIT_FAILURE);
        }
    }

    printf("The main thread is ready.\n");

    pthread_barrier_wait(&barrier);

    printf("The main thread passed the barrier!\n");

    for (i = 0; i < THREAD_COUNT; i++) {
        err = pthread_join(tid[i], NULL);
        if (err != 0) {
            fprintf(stderr, "pthread_join: %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }

    pthread_barrier_destroy(&barrier);

    return EXIT_SUCCESS;
}
src/knowing_nbcores.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

/**
 * @file knowing_nbcores.c
 *
 * A simple program used to know how many cores (online processors) your
 * system has, using sysconf(_SC_NPROCESSORS_ONLN). This value is not
 * required by POSIX, but it is provided by Linux and macOS.
 */

int main(void) {
    long cores = sysconf(_SC_NPROCESSORS_ONLN);

    if (cores == -1) {
        perror("sysconf");
        exit(EXIT_FAILURE);
    }
    printf("Number of cores: %ld\n", cores);

    return EXIT_SUCCESS;
}
src/matrix_product_threads.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* malloc(), free(), exit(), rand_r(), RAND_MAX */
#include <string.h>     /* strerror() */
#include <time.h>       /* clock_gettime() */

/**
 * @file matrix_product_threads.c
 * @brief Running example: square matrix product R = A x B computed by
 * 4 threads, one per quadrant of R.
 *
 * Lecture: chapter os-08 "Threads" (running example "découpage en
 * quadrants").
 *
 * Each element R[i][j] is the dot product of row i of A and column j of B:
 * it is computed independently of the others. Each thread computes one
 * quadrant of R (0: top left, 1: top right, 2: bottom left, 3: bottom
 * right), so no two threads write to the same place: no lock is needed.
 *
 * The program multiplies two n x n matrices (n even, 512 by default or
 * given as argument) with one thread, then with 4 threads, checks that both
 * results are equal and displays both durations.
 *
 * Key points:
 *   - each thread receives the address of its own args_t structure;
 *   - args[] remains valid until the pthread_join() calls;
 *   - small matrices: the multi-thread version is slower, since creating
 *     and joining the threads costs more than the computation;
 *   - the matrices are filled with rand_r() and a private seed (see the
 *     slide "Correction : les versions _r").
 *
 * \code{.bash}
 *   $ ./matrix_product_threads 1024
 *   n = 1024 : 1 thread 2.84 s, 4 threads 0.93 s, résultats identiques
 * \endcode
 */

typedef struct matrix {
    int rows;
    int columns;
    double **matrix;
} matrix_t;

typedef struct args_t {  /* one per thread */
    int quadrant;        /* 0 to 3 */
    matrix_t *m1;        /* A */
    matrix_t *m2;        /* B */
    matrix_t *answer;    /* R = A x B */
} args_t;

void multi_thread(matrix_t *m1, matrix_t *m2, matrix_t *answer);
void *product_matrix_thread(void *args);

/**
 * @brief Handles a fatal error and exits.
 * @param msg Error message displayed before exiting.
 */
void handle_fatal_error_and_exit(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Allocates an n x n matrix (contents not initialized).
 */
matrix_t *create_matrix(int n) {
    matrix_t *m = malloc(sizeof *m);
    if (m == NULL) {
        handle_fatal_error_and_exit("malloc");
    }
    m->rows = n;
    m->columns = n;
    m->matrix = malloc(n * sizeof(double *));
    if (m->matrix == NULL) {
        handle_fatal_error_and_exit("malloc");
    }
    for (int i = 0; i < n; i++) {
        m->matrix[i] = malloc(n * sizeof(double));
        if (m->matrix[i] == NULL) {
            handle_fatal_error_and_exit("malloc");
        }
    }
    return m;
}

/**
 * @brief Frees a matrix created by create_matrix().
 */
void free_matrix(matrix_t *m) {
    for (int i = 0; i < m->rows; i++) {
        free(m->matrix[i]);
    }
    free(m->matrix);
    free(m);
}

/**
 * @brief Fills a matrix with pseudo-random values in [0, 1).
 */
void fill_matrix(matrix_t *m, unsigned int graine) {
    for (int i = 0; i < m->rows; i++) {
        for (int j = 0; j < m->columns; j++) {
            m->matrix[i][j] = rand_r(&graine) / ((double) RAND_MAX + 1);
        }
    }
}

/**
 * @brief Computes the quadrant a->quadrant of R = A x B.
 */
void *product_matrix_thread(void *args) {
    args_t *a = args;
    double **A = a->m1->matrix, **B = a->m2->matrix;
    double **R = a->answer->matrix;
    int h = a->answer->rows / 2;     /* half size */
    int i0 = (a->quadrant / 2) * h;  /* first row */
    int j0 = (a->quadrant % 2) * h;  /* first column */

    for (int i = i0; i < i0 + h; i++) {
        for (int j = j0; j < j0 + h; j++) {
            R[i][j] = 0.0;
            for (int k = 0; k < a->m1->columns; k++) {
                R[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    return NULL;
}

/**
 * @brief Computes R = A x B with 4 threads, one per quadrant.
 */
void multi_thread(matrix_t *m1, matrix_t *m2, matrix_t *answer) {
    pthread_t tid[4];
    args_t args[4];           /* one block per thread */
    int err;

    for (int q = 0; q < 4; q++) {
        args[q] = (args_t){ q, m1, m2, answer };
        err = pthread_create(&tid[q], NULL,
                             product_matrix_thread, &args[q]);
        if (err != 0) {
            fprintf(stderr, "pthread_create : %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }
    for (int q = 0; q < 4; q++) {
        pthread_join(tid[q], NULL);
    }
}

/**
 * @brief Computes R = A x B in the calling thread (reference version).
 */
void single_thread(matrix_t *m1, matrix_t *m2, matrix_t *answer) {
    for (int q = 0; q < 4; q++) {
        args_t a = { q, m1, m2, answer };
        product_matrix_thread(&a);
    }
}

/**
 * @brief Returns the current time in seconds (monotonic clock).
 */
double now(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec + ts.tv_nsec / 1e9;
}

int main(int argc, char *argv[]) {
    int n = 512;
    double t0, t1, t2;
    int identical = 1;

    if (argc > 1) {
        char *end;
        n = (int) strtol(argv[1], &end, 10);
        if (*end != '\0') {
            n = 0;  /* not a number: rejected below */
        }
    }
    if (n <= 0 || n % 2 != 0) {
        fprintf(stderr, "usage : %s [n pair > 0]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    matrix_t *a = create_matrix(n);
    matrix_t *b = create_matrix(n);
    matrix_t *r1 = create_matrix(n);
    matrix_t *r4 = create_matrix(n);
    fill_matrix(a, 1);
    fill_matrix(b, 2);

    t0 = now();
    single_thread(a, b, r1);
    t1 = now();
    multi_thread(a, b, r4);
    t2 = now();

    for (int i = 0; i < n && identical; i++) {
        for (int j = 0; j < n; j++) {
            if (r1->matrix[i][j] != r4->matrix[i][j]) {
                identical = 0;
                break;
            }
        }
    }
    printf("n = %d : 1 thread %.2f s, 4 threads %.2f s, résultats %s\n",
           n, t1 - t0, t2 - t1, identical ? "identiques" : "DIFFÉRENTS");

    free_matrix(a);
    free_matrix(b);
    free_matrix(r1);
    free_matrix(r4);

    return EXIT_SUCCESS;
}
src/pb_reentrant.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */

/**
 * @file pb_reentrant.c
 * @see without_pb_reentrant.c
 *
 * A simple program to show the importance of using "reentrant" functions.
 *
 * f() is the example implementation of rand() given by the C standard: its
 * state (next) is a hidden static variable shared by all the threads. The
 * threads modify it concurrently (data race) and the sequence of values
 * depends on the scheduling. Correction: without_pb_reentrant.c.
 *
 * What to observe: the 4 threads display 4 different values (16838, 5758,
 * 10113, 17515, in an order that changes): they share one sequence, each
 * call moves the hidden state for everybody. With without_pb_reentrant.c,
 * every thread displays 16838: each one has its own sequence.
 */

#define THREADS 4


int f(void) {
    static unsigned int next = 1;

    next = next * 1103515245 + 12345;
    return (int) ((next / 65536) % 32768);
}

void *doit(void *vargp) {
    (void) vargp; /* Deactivate warning */
    printf("[%lu]: val = %d\n", (unsigned long) pthread_self(), f());
    return NULL;
}

int main(void) {
    int i;
    int err;
    pthread_t tid[THREADS];

    for (i = 0; i < THREADS; i++) {
        if ((err = pthread_create(&tid[i], NULL, doit, NULL)) != 0) {
            fprintf(stderr, "pthread_create : %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < THREADS; i++) {
        if ((err = pthread_join(tid[i], NULL)) != 0) {
            fprintf(stderr, "pthread_join : %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
src/pthread_barrier.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "pthread_barrier.h"

int pthread_barrier_init(pthread_barrier_t *barrier, const void *attr, unsigned count) {
    int status;

    (void) attr;  /* attributes are not supported */
    status = pthread_mutex_init(&barrier->mutex, NULL);
    if (status != 0) return status;
    status = pthread_cond_init(&barrier->cond, NULL);
    if (status != 0) {
        pthread_mutex_destroy(&barrier->mutex);
        return status;
    }
    barrier->count = count;
    barrier->waiting = 0;
    barrier->generation = 0;
    return 0;
}

int pthread_barrier_wait(pthread_barrier_t *barrier) {
    pthread_mutex_lock(&barrier->mutex);
    unsigned generation = barrier->generation;
    barrier->waiting++;
    if (barrier->waiting < barrier->count) {
        /* while loop: spurious wakeups; the predicate is "barrier opened" */
        while (generation == barrier->generation) {
            pthread_cond_wait(&barrier->cond, &barrier->mutex);
        }
        pthread_mutex_unlock(&barrier->mutex);
        return 0;
    } else {
        barrier->waiting = 0; /* reset for next use */
        barrier->generation++;
        pthread_cond_broadcast(&barrier->cond);
        pthread_mutex_unlock(&barrier->mutex);
        return PTHREAD_BARRIER_SERIAL_THREAD;
    }
}

int pthread_barrier_destroy(pthread_barrier_t *barrier) {
    pthread_cond_destroy(&barrier->cond);
    pthread_mutex_destroy(&barrier->mutex);
    return 0;
}
src/test_fork.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h> /* necessary for wait */
#include <sys/wait.h> /* necessary for wait */

/**
 * @file test_fork.c
 *
 * A simple program to test fork vs threads (see \c test_pthread.c).
 * The elapsed (wall-clock) time is measured with clock_gettime(): clock()
 * would only count the CPU time of the parent, not that of its children.
 *
 * Compile using gcc -Wall -Wextra test_fork.c -o test_fork
 */

#define NB_FORKS 50000

/**
 * Handles a fatal error. It displays a message, then exits.
 */
void handle_fatal_error(char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

void do_little(void) {
    int i;

    i = 0;
    i = i + 2;

    exit(EXIT_SUCCESS);
}

int main(void) {
    pid_t pid;
    int status;
    int i;
    struct timespec begin_time;
    struct timespec end_time;
    double duration;

    status = 0;

    clock_gettime(CLOCK_MONOTONIC, &begin_time);

    for (i = 0; i < NB_FORKS; i++) {
        if ((pid = fork()) == -1) {
            handle_fatal_error("Error when trying to fork");
        } else if (pid == 0) {
            do_little();
        } else {
            waitpid(pid, &status, 0);
        }
    }

    clock_gettime(CLOCK_MONOTONIC, &end_time);
    duration = (end_time.tv_sec - begin_time.tv_sec)
               + (end_time.tv_nsec - begin_time.tv_nsec) / 1e9;
    printf("%2.1f seconds\n", duration);

    return EXIT_SUCCESS;
}  
src/test_pthread.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define NB_THREADS 50000
#define OK 0

/**
 * @file test_pthread.c
 *
 * A simple program to test threads vs the fork one (see \c test_fork.c).
 * The elapsed (wall-clock) time is measured with clock_gettime().
 *
 * Compile using gcc -Wall -Wextra test_pthread.c -o test_pthread -pthread
 */

void *do_little(void *unused) {
    (void) unused; /* Deactivate warning */
    int i;

    i = 0;
    i = i + 2;

    pthread_exit(NULL);
}

int main(void) {
    int action, i;
    pthread_t tid;
    pthread_attr_t attr;
    struct timespec begin_time;
    struct timespec end_time;
    double duration;

    clock_gettime(CLOCK_MONOTONIC, &begin_time);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for (i = 0; i < NB_THREADS; i++) {
        action = pthread_create(&tid, &attr, do_little, NULL);
        if (action != OK) {
            fprintf(stderr, "pthread_create: %s\n", strerror(action));
            exit(EXIT_FAILURE);
        }

        /* Attente du thread */
        action = pthread_join(tid, NULL);
        if (action != OK) {
            fprintf(stderr, "pthread_join: %s\n", strerror(action));
            exit(EXIT_FAILURE);
        }
    }
    clock_gettime(CLOCK_MONOTONIC, &end_time);
    duration = (end_time.tv_sec - begin_time.tv_sec)
               + (end_time.tv_nsec - begin_time.tv_nsec) / 1e9;
    printf("%2.1f seconds\n", duration);

    pthread_attr_destroy(&attr);

    return EXIT_SUCCESS;
}
src/thread_01.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

/**
 * @file thread_01.c
 *
 * A simple program using 2 POSIX threads.
 *
 * WARNING: synchronization is deliberately missing. Thread A writes
 * global_value while thread B reads it: the displayed values are
 * unpredictable (a data race). The sleep(1) in main() does not synchronize
 * anything: only pthread_join() guarantees that the threads are finished.
 *
 * Compile with gcc -Wall -Wextra -pedantic -std=c11 -pthread thread_01.c
 */

int global_value = -10;

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

void *do_A(void *arg) {
    int i;
    int n;

    n = *(int *) arg;

    for (i = 0; i < n; i++) {
        global_value = i;
    }

    pthread_exit(NULL);
}

void *do_B(void *arg) {
    int i;
    int n;

    n = *(int *) arg;

    for (i = 0; i < n; i++) {
        printf("%d\n", global_value);
    }
    pthread_exit(NULL);
}

int main(void) {
    pthread_t thA;
    pthread_t thB;
    int n = 10;

    check(pthread_create(&thA, NULL, do_A, &n), "pthread_create");
    check(pthread_create(&thB, NULL, do_B, &n), "pthread_create");

    /* ... */
    sleep(1);

    /* The main thread is waiting for A and B to finish */
    printf("The main thread is waiting for A and B to finish\n");
    check(pthread_join(thB, NULL), "pthread_join");
    check(pthread_join(thA, NULL), "pthread_join");

    return EXIT_SUCCESS;
}
src/thread_02.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

/**
 * @file thread_02.c
 *
 * A simple program using 3 POSIX threads: main creates A and B, B creates C
 * and waits for it. What to observe: the blocks of letters of the threads
 * interleave (compare with thread_02_withmutex.c).
 *
 * Compile with gcc -Wall -Wextra -pedantic -std=c11 -pthread thread_02.c
 */

#define ITERATIONS 100000

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

void display(int n, char letter) {
    int i;
    int j;

    for (j = 0; j < n; j++) {
        for (i = 0; i < ITERATIONS; i++) {
            printf("%c", letter);
        }
        fflush(stdout);
    }
}

void *threadA(void *unused) {
    (void) unused; /* Deactivate warning */
    display(100, 'A');
    printf("\n End of the thread A\n");
    fflush(stdout);

    pthread_exit(NULL);
}

void *threadC(void *unused) {
    (void) unused; /* Deactivate warning */
    display(150, 'C');

    printf("\n End of the thread C\n");
    fflush(stdout);

    pthread_exit(NULL);
}

void *threadB(void *unused) {
    (void) unused; /* Deactivate warning */
    pthread_t thC;

    check(pthread_create(&thC, NULL, threadC, NULL), "pthread_create");
    display(100, 'B');

    printf("\n Thread B is waiting for thread C\n");
    check(pthread_join(thC, NULL), "pthread_join");

    printf("\n End of the thread B\n");
    fflush(stdout);

    pthread_exit(NULL);
}

int main(void) {
    pthread_t thA;
    pthread_t thB;

    printf(" Creation of the thread A\n");
    check(pthread_create(&thA, NULL, threadA, NULL), "pthread_create");
    printf(" Creation of the thread B\n");
    check(pthread_create(&thB, NULL, threadB, NULL), "pthread_create");
    sleep(1);

    /* The main thread is waiting for A and B to finish */
    printf("The main thread is waiting for A and B to finish\n");
    check(pthread_join(thA, NULL), "pthread_join");
    check(pthread_join(thB, NULL), "pthread_join");

    return EXIT_SUCCESS;
}
src/thread_02_withmutex.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

/**
 * @file thread_02_withmutex.c
 *
 * A simple program using 3 POSIX threads and a mutex: same as thread_02.c,
 * but each block of letters is displayed under the protection of the mutex,
 * so that the blocks of the different threads no longer interleave.
 *
 * Compile with gcc -Wall -Wextra -pedantic -std=c11 -pthread thread_02_withmutex.c
 */

#define ITERATIONS 100000

pthread_mutex_t mutex;

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

void display(int n, char letter) {
    int i;
    int j;

    for (j = 0; j < n; j++) {
        pthread_mutex_lock(&mutex);
        for (i = 0; i < ITERATIONS; i++) {
            printf("%c", letter);
        }
        fflush(stdout);
        pthread_mutex_unlock(&mutex);
    }
}

void *threadA(void *unused) {
    (void) unused; /* Deactivate warning */
    display(100, 'A');
    printf("\n End of the thread A\n");
    fflush(stdout);

    pthread_exit(NULL);
}

void *threadC(void *unused) {
    (void) unused; /* Deactivate warning */
    display(150, 'C');

    printf("\n End of the thread C\n");
    fflush(stdout);

    pthread_exit(NULL);
}

void *threadB(void *unused) {
    (void) unused; /* Deactivate warning */
    pthread_t thC;

    check(pthread_create(&thC, NULL, threadC, NULL), "pthread_create");
    display(100, 'B');

    printf("\n Thread B is waiting for thread C\n");
    check(pthread_join(thC, NULL), "pthread_join");

    printf("\n End of the thread B\n");
    fflush(stdout);

    pthread_exit(NULL);
}

int main(void) {
    pthread_t thA;
    pthread_t thB;

    pthread_mutex_init(&mutex, NULL);
    printf(" Creation of the thread A\n");
    check(pthread_create(&thA, NULL, threadA, NULL), "pthread_create");
    printf(" Creation of the thread B\n");
    check(pthread_create(&thB, NULL, threadB, NULL), "pthread_create");
    sleep(1);

    /* The main thread is waiting for A and B to finish */
    printf("The main thread is waiting for A and B to finish\n");
    check(pthread_join(thA, NULL), "pthread_join");
    check(pthread_join(thB, NULL), "pthread_join");
    pthread_mutex_destroy(&mutex);

    return EXIT_SUCCESS;
}
src/thread_arg_pitfall.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdio.h>      /* printf() */
#include <stdlib.h>     /* EXIT_SUCCESS */
#include <string.h>  /* strerror() */

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

/**
 * @file thread_arg_pitfall.c
 * @brief Pitfall: passing the address of a loop variable to several
 * threads, and its correction.
 *
 * Lecture: chapter os-08 "Threads" ("Exercice 1 - qu'affiche ce
 * programme ?" and its correction).
 *
 * Version 1 (wrong): the four threads receive the same address, that of i,
 * and each one reads i when it runs, while main() modifies it. The values
 * are unpredictable and may be duplicated, e.g. 2, 2, 4, 0.
 *
 * Version 2 (correct): one slot per thread, which no longer changes.
 *
 * Rule: never pass the address of a variable that changes afterwards.
 *
 * \code{.bash}
 *   $ ./thread_arg_pitfall
 *   version 1 (FAUX) : &i partagé
 *   thread 2
 *   thread 2
 *   thread 4
 *   thread 0
 *   version 2 : un argument par thread
 *   thread 0
 *   thread 1
 *   thread 3
 *   thread 2
 * \endcode
 */

void *f(void *arg) {
    printf("thread %d\n", *(int *) arg);
    return NULL;
}

int main(void) {
    pthread_t t[4];
    int i;

    printf("version 1 (FAUX) : &i partagé\n");
    for (i = 0; i < 4; i++) {
        check(pthread_create(&t[i], NULL, f, &i), "pthread_create");        /* WRONG */
    }
    for (i = 0; i < 4; i++) {
        check(pthread_join(t[i], NULL), "pthread_join");
    }

    printf("version 2 : un argument par thread\n");
    int ids[4];                  /* one argument per thread */
    for (int k = 0; k < 4; k++) {
        ids[k] = k;
        check(pthread_create(&t[k], NULL, f, &ids[k]), "pthread_create");
    }
    for (int k = 0; k < 4; k++) {
        check(pthread_join(t[k], NULL), "pthread_join");
    }

    return EXIT_SUCCESS;
}
src/thread_detached.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>    /* pthread_create(), pthread_attr_*(), pthread_exit() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file thread_detached.c
 * @brief Creates a detached thread using the PTHREAD_CREATE_DETACHED
 * attribute.
 *
 * Lecture: chapter os-08 "Threads" ("Thread détaché - exemple").
 *
 * Key points:
 *   - the resources of a detached thread are freed automatically when it
 *     ends; pthread_join() is impossible;
 *   - the attribute object is only read at creation: it can be destroyed
 *     right after pthread_create();
 *   - main() ends with pthread_exit(), which lets worker() finish; a
 *     return would call exit() and kill it.
 *
 * \code{.bash}
 *   $ ./thread_detached
 *   Thread détaché >> Bonjour
 * \endcode
 */

void *worker(void *arg) {
    printf("Thread détaché >> %s\n", (char *) arg);
    return NULL;
}

int main(void) {
    pthread_t tid;
    pthread_attr_t attr;
    int err;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    err = pthread_create(&tid, &attr, worker, "Bonjour");
    if (err != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    pthread_attr_destroy(&attr);
    pthread_exit(NULL);     /* no join possible */
}
src/thread_hello.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>    /* pthread_create(), pthread_join(), pthread_self() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* strerror() */

/**
 * @file thread_hello.c
 * @brief First Pthread program: creates one thread and waits for it.
 *
 * Lecture: chapter os-08 "Threads" ("Premier programme").
 *
 * The main thread creates a secondary thread, displays both identifiers,
 * then waits for the secondary thread with pthread_join().
 *
 * Key points:
 *   - the secondary thread retrieves with pthread_self() the identifier
 *     stored in tid1;
 *   - the order of the lines is not guaranteed;
 *   - converting a pthread_t to unsigned long is not portable (debugging
 *     only);
 *   - Pthread functions return an error code and do not set errno.
 *
 * \code{.bash}
 *   $ gcc -Wall -pthread -o thread_hello thread_hello.c
 *   $ ./thread_hello
 *   principal : 140245863241536
 *   secondaire : 140245854848768
 *   Bonjour de la part de 140245854848768
 * \endcode
 */

void *todo(void *arg) {
    (void) arg;
    printf("Bonjour de la part de %lu\n",
           (unsigned long) pthread_self());
    return NULL;              /* = pthread_exit(NULL) */
}

int main(void) {
    pthread_t tid1;
    int err;

    err = pthread_create(&tid1, NULL, todo, NULL);
    if (err != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    printf("principal : %lu\nsecondaire : %lu\n",
           (unsigned long) pthread_self(),
           (unsigned long) tid1);
    pthread_join(tid1, NULL);

    return EXIT_SUCCESS;
}
src/thread_shared_variables.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdio.h>      /* printf() */
#include <stdlib.h>     /* EXIT_SUCCESS */

/**
 * @file thread_shared_variables.c
 * @brief Program to analyse: which variables are shared by the threads?
 *
 * Lecture: chapter os-08 "Threads" ("Exemple - un programme à analyser").
 *
 * | Variable              | Instances | Location              | Shared?       |
 * |-----------------------|-----------|-----------------------|---------------|
 * | ptr (global)          | 1         | data segment          | yes           |
 * | svar (local static)   | 1         | data segment          | yes           |
 * | msg (local to main)   | 1         | stack of main thread  | yes, via ptr  |
 * | i, tid (local to main)| 1         | stack of main thread  | no            |
 * | myid (local to todo)  | 2         | one in each stack     | no            |
 *
 * Key points:
 *   - (void *)i passes the value of i, not its address;
 *   - the secondary threads read msg, stored in the stack of the main
 *     thread, through the global pointer ptr;
 *   - ++svar is an unprotected concurrent access.
 *
 * GCC (>= 12) warns "storing the address of local variable 'msg' in 'ptr'":
 * expected, it is the point of the example; msg stays valid because main()
 * joins the threads before returning.
 *
 * \code{.bash}
 *   $ ./thread_shared_variables
 *   [0] : P1 (svar=1)
 *   [1] : P2 (svar=2)
 * \endcode
 */

char **ptr;                           /* global */

void *todo(void *vargp) {
    long myid = (long) vargp;         /* local */
    static int svar = 0;              /* static */

    printf("[%ld] : %s (svar=%d)\n", myid, ptr[myid], ++svar);
    return NULL;
}

int main(void) {
    pthread_t tid[2];
    char *msg[2] = { "P1", "P2" };    /* local */

    ptr = msg;
    for (long i = 0; i < 2; i++) {
        pthread_create(&tid[i], NULL, todo, (void *) i);
    }
    for (long i = 0; i < 2; i++) {
        pthread_join(tid[i], NULL);
    }
    return EXIT_SUCCESS;
}
src/thread_square.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <pthread.h>    /* pthread_create(), pthread_join() */
#include <stdio.h>      /* printf(), fprintf() */
#include <stdlib.h>     /* malloc(), free(), exit() */
#include <string.h>     /* strerror() */

/**
 * @file thread_square.c
 * @brief Passes an argument to a thread and gets its result back.
 *
 * Lecture: chapter os-08 "Threads" ("Passer un argument, récupérer un
 * résultat").
 *
 * The thread receives the address of a long, computes its square in a
 * block allocated on the heap and returns its address. The main thread
 * gets it back with pthread_join(), displays it, then frees it.
 *
 * Key points:
 *   - never return the address of a local variable: the stack of the
 *     thread disappears with it;
 *   - several arguments: pass the address of a structure.
 *
 * \code{.bash}
 *   $ ./thread_square
 *   49
 * \endcode
 */

void *carre(void *arg) {
    long n = *(long *) arg;          /* argument */
    long *res = malloc(sizeof *res);
    if (res == NULL) {
        return NULL;
    }
    *res = n * n;
    return res;                      /* on the heap */
}

int main(void) {
    pthread_t tid;
    long n = 7;
    void *ret;
    int err;

    err = pthread_create(&tid, NULL, carre, &n);
    if (err != 0) {
        fprintf(stderr, "pthread_create : %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    pthread_join(tid, &ret);         /* ret = res */
    if (ret == NULL) {
        fprintf(stderr, "carre : malloc a échoué\n");
        exit(EXIT_FAILURE);
    }
    printf("%ld\n", *(long *) ret);  /* 49 */
    free(ret);

    return EXIT_SUCCESS;
}
src/thread_with_conditions.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */

/**
 * @file thread_with_conditions.c
 *
 * Example using pthreads and conditions.
 * The program creates NUM_THREADS threads. (NUM_THREADS-1) of those threads
 * increment a "count" variable, while the last one reads the value of "count".
 * When "count" reaches a limit (COUNT_LIMIT), the waiting thread is signaled by
 * one of the incrementing threads. The waiting thread "awakens" and then
 * modifies count. The program continues until the incrementing threads reach
 * TOTAL_COUNT. The main program prints the final value of count.
 * This example is adapted from the code at:
 * https://hpc-tutorials.llnl.gov/posix/
 *
 * @author Blaise Barney -- Lawrence Livermore National Laboratory (03/07/2017)
 * @author Alain Lebret (06/08/2017)
 * @version 1.0
 * @date 2017-06-08
 */

#define NUM_THREADS  4
#define TOTAL_COUNT 10
#define COUNT_LIMIT 12

int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

void *inc_count(void *t) {
    int i;
    long my_id = (long) t;

    for (i = 0; i < TOTAL_COUNT; i++) {
        pthread_mutex_lock(&count_mutex);
        count++;

        /*
         * Check the value of count and signal waiting thread when
         * condition is reached. Note that this occurs while mutex
         * is locked.
         */
        if (count == COUNT_LIMIT) {
            printf("inc_count(): thread %ld, count = %d  Threshold reached. ",
                   my_id, count);
            pthread_cond_signal(&count_threshold_cv);
            printf("Just sent signal.\n");
        }
        printf("inc_count(): thread %ld, count = %d, unlocking mutex\n",
               my_id, count);
        pthread_mutex_unlock(&count_mutex);

        /* Do some work so threads can alternate on mutex lock */
        sleep(1);
    }
    pthread_exit(NULL);
}

void *watch_count(void *t) {
    long my_id = (long) t;

    printf("watch_count(): thread %ld\n", my_id);

    /*
     * Lock mutex and wait for signal.  Note that the pthread_cond_wait
     * routine will automatically and atomically unlock mutex while it
     * waits. Also, note that if COUNT_LIMIT is reached before this routine
     * is run by the waiting thread, the loop will be skipped to prevent
     * pthread_cond_wait from never returning.
     */
    pthread_mutex_lock(&count_mutex);
    while (count < COUNT_LIMIT) {
        printf("watch_count(): thread %ld Count= %d. Going into wait...\n", my_id, count);
        pthread_cond_wait(&count_threshold_cv, &count_mutex);
        printf("watch_count(): thread %ld Condition signal received. Count= %d\n", my_id, count);
    }
    printf("watch_count(): thread %ld Updating the value of count...\n", my_id);
    count += 125;
    printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
    printf("watch_count(): thread %ld Unlocking mutex.\n", my_id);
    pthread_mutex_unlock(&count_mutex);
    pthread_exit(NULL);
}

int main(void) {
    int i;
    long t1;
    long t2;
    long t3;
    long t4;
    pthread_t threads[NUM_THREADS];
    pthread_attr_t attr;

    t1 = 1;
    t2 = 2;
    t3 = 3;
    t4 = 4;

    /* Initialize mutex and condition variable objects */
    pthread_mutex_init(&count_mutex, NULL);
    pthread_cond_init(&count_threshold_cv, NULL);

    /* For portability, explicitly create threads in a joinable state */
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    check(pthread_create(&threads[0], &attr, watch_count, (void *) t1), "pthread_create");
    check(pthread_create(&threads[1], &attr, inc_count, (void *) t2), "pthread_create");
    check(pthread_create(&threads[2], &attr, inc_count, (void *) t3), "pthread_create");
    check(pthread_create(&threads[3], &attr, inc_count, (void *) t4), "pthread_create");

    /* Wait for all threads to complete */
    for (i = 0; i < NUM_THREADS; i++) {
        check(pthread_join(threads[i], NULL), "pthread_join");
    }
    printf("main(): waited and joined with %d threads. Final value of count = %d. Done.\n",
           NUM_THREADS, count);

    /* Clean up and exit */
    pthread_attr_destroy(&attr);
    pthread_mutex_destroy(&count_mutex);
    pthread_cond_destroy(&count_threshold_cv);

    return EXIT_SUCCESS;
}
src/thread_with_shm_and_mutex.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

/**
 * @file thread_with_shm_and_mutex.c
 *
 * A simple program that creates 4 producer threads and 1 consumer. They all
 * share a memory using a mutex. When the producers are finished, the main
 * thread sets producers_done and the consumer stops once the buffer is empty.
 *
 * Note: the threads test memory.state in a loop (active polling). A
 * condition variable avoids this wasted time: see thread_with_conditions.c.
 *
 * Compile with gcc -Wall -Wextra thread_with_shm_and_mutex.c -pthread
 */

#define BUFFER_SPACE 0
#define BUFFER_FULL 1
#define ITERATIONS 100000

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

struct {
    int state; /* BUFFER_SPACE or BUFFER_FULL */
    int value;
} memory;

int producers_done = 0; /* protected by the mutex */

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

/**
 * Consumer task that reads the shared memory.
 */
void *consume(void *pv) {
    (void) pv; /* Deactivate warning */
    int finished = 0;

    while (!finished) {
        pthread_mutex_lock(&mutex);
        if (memory.state == BUFFER_FULL) {
            /* use the value */
            printf("%d\n", memory.value);
            memory.state = BUFFER_SPACE;
        } else if (producers_done) {
            finished = 1; /* buffer empty and nothing more will come */
        }
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return NULL;
}

/**
 * Producer task that writes on the shared memory.
 */
void *produce(void *pv) {
    (void) pv; /* Deactivate warning */
    int i = 0;

    while (i++ < ITERATIONS) {
        pthread_mutex_lock(&mutex);
        if (memory.state == BUFFER_SPACE) {
            /* doing some stuff */
            memory.state = BUFFER_FULL;
            memory.value = memory.value + 1;
        }
        pthread_mutex_unlock(&mutex);
        /* sleep(1); */
    }
    pthread_exit(NULL);
}

int main(void) {
    pthread_t th1, th2, th3, th4, th5;

    /* Creation of the threads */
    check(pthread_create(&th1, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th2, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th3, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th4, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th5, NULL, consume, 0), "pthread_create");

    /* The main thread waits for the producers, then tells the consumer */
    check(pthread_join(th1, NULL), "pthread_join");
    check(pthread_join(th2, NULL), "pthread_join");
    check(pthread_join(th3, NULL), "pthread_join");
    check(pthread_join(th4, NULL), "pthread_join");

    pthread_mutex_lock(&mutex);
    producers_done = 1;
    pthread_mutex_unlock(&mutex);

    check(pthread_join(th5, NULL), "pthread_join");

    return EXIT_SUCCESS;
}
src/thread_with_shm_without_mutex.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

/**
 * @file thread_with_shm_without_mutex.c
 *
 * A simple program that creates 4 producer threads and 1 consumer. They all
 * share a memory without using a mutex.
 *
 * WARNING: synchronization is deliberately missing. Several producers may
 * see BUFFER_SPACE at the same time and all increment the value, and the
 * compiler may even keep memory.state in a register: the behavior is
 * wrong (data race). See thread_with_shm_and_mutex.c. Ctrl-C to stop.
 *
 * Compile with gcc -Wall -Wextra -pedantic -std=c11 -pthread thread_with_shm_without_mutex.c
 * @date 2012-04-10
 */

#define BUFFER_SPACE 0
#define BUFFER_FULL  1

struct {
    int state; /* BUFFER_SPACE or BUFFER_FULL */
    int value;
} memory;

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

/**
 * Consumer task that reads the shared memory.
 */
void *consume(void *pv) {
    (void) pv; /* Deactivate warning */
    while (1) {
        if (memory.state == BUFFER_FULL) {
            /* get the value */
            printf("%d\n", memory.value);
            memory.state = BUFFER_SPACE;
        }
        sleep(2);
    }
    /* Unreachable */
}

/**
 * Producer task that writes on the shared memory.
 */
void *produce(void *pv) {
    (void) pv; /* Deactivate warning */
    while (1) {
        if (memory.state == BUFFER_SPACE) {
            /* doing some stuff ... */
            memory.state = BUFFER_FULL;
            memory.value = memory.value + 1;
        }
        /* sleep(1); */
    }
    /* Unreachable */
}

int main(void) {
    pthread_t th1;
    pthread_t th2;
    pthread_t th3;
    pthread_t th4;
    pthread_t th5;

    /* Creation of the threads */
    check(pthread_create(&th1, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th2, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th3, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th4, NULL, produce, 0), "pthread_create");
    check(pthread_create(&th5, NULL, consume, 0), "pthread_create");

    printf("4 producers and 1 consumer have been created\n");

    /* The main thread is waiting for all threads to finish */
    check(pthread_join(th1, NULL), "pthread_join");
    check(pthread_join(th2, NULL), "pthread_join");
    check(pthread_join(th3, NULL), "pthread_join");
    check(pthread_join(th4, NULL), "pthread_join");
    check(pthread_join(th5, NULL), "pthread_join");

    return EXIT_SUCCESS;
}
src/thread_with_signal.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <errno.h>

/**
 * @file thread_with_signal.c
 *
 * A simple program using threads and signal: after 10 seconds, main()
 * sends SIGINT to the secondary thread with pthread_kill(); the handler
 * (async-signal-safe: write() only) sets a flag that stops the thread.
 *
 * Compile with gcc -Wall -Wextra -pedantic -std=c11 -pthread thread_with_signal.c
 */

typedef struct data {
    char name[12];
    int age;
} data_t;

static volatile sig_atomic_t stop_requested = 0;

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

void handle_signal(int sig) {
    (void) sig;  /* Mark sig as unused */
    int saved_errno = errno;   /* write() may modify errno */
    write(STDOUT_FILENO, "Caught signal SIGINT\n", 21);
    errno = saved_errno;
    stop_requested = 1;
}

void *func(void *arg) {
    data_t *p = (data_t *) arg;

    while (!stop_requested) {
        fprintf(stderr, "This is from thread function\n");
        snprintf(p->name, sizeof(p->name), "Linux Lover");
        p->age = 55;
        sleep(2);
    }
    return NULL;
}

int main(void) {
    pthread_t tid;
    pthread_attr_t attr;
    data_t d;
    data_t *ptr = &d;
    struct sigaction action;

    action.sa_handler = &handle_signal;
    sigemptyset(&action.sa_mask);
    action.sa_flags = 0;
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    pthread_attr_init(&attr);
    check(pthread_create(&tid, &attr, func, ptr), "pthread_create");
    sleep(10);
    pthread_kill(tid, SIGINT);

    check(pthread_join(tid, NULL), "pthread_join");
    pthread_attr_destroy(&attr);
    fprintf(stderr, "Name: %s\n", ptr->name);
    fprintf(stderr, "Age: %d\n", ptr->age);

    return EXIT_SUCCESS;
}
src/timer_and_citizens.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @file timer_and_citizens.c
 *
 * @brief A timer thread wakes up citizen threads with pthread_cond_broadcast().
 *
 * Inspired from Lloyd Rochester.
 * See: https://lloydrochester.com
 *
 * A timer thread wakes up all the citizen threads with
 * pthread_cond_broadcast(). The predicate day_has_begun, protected by
 * day_mutex, makes the program correct whatever the order of the threads:
 * a citizen that arrives after the broadcast does not wait, and a spurious
 * wakeup puts the citizen back to sleep (while loop).
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */
#include <pthread.h>
#include <unistd.h>

#define NB_THREADS 6

void *timer_begin_new_day(void *data);

void *citizen_spends_his_day(void *data);

pthread_mutex_t day_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t citizen_can_wake_up_cond = PTHREAD_COND_INITIALIZER;
int day_has_begun = 0;         /* the predicate, protected by day_mutex */
int thread_ids[NB_THREADS] = {0, 1, 2, 3, 4, 5};

/**
 * Stops the program if a pthread_*() call failed: these functions return an
 * error number (0 on success) and do not set errno.
 */
static void check(int err, const char *what) {
    if (err != 0) {
        fprintf(stderr, "%s : %s\n", what, strerror(err));
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    int i;
    pthread_t threads[NB_THREADS];

    for (i = 1; i < NB_THREADS; i++) {
        check(pthread_create(&threads[i], NULL, citizen_spends_his_day, &thread_ids[i]), "pthread_create");
    }

    /*
     * the citizen threads have probably started and are waiting on the
     * condition: this sleep() only makes the output readable, the
     * predicate day_has_begun ensures correctness.
     */
    sleep(1);
    check(pthread_create(&threads[0], NULL, timer_begin_new_day, &thread_ids[0]), "pthread_create");

    for (i = 0; i < NB_THREADS; i++) {
        check(pthread_join(threads[i], NULL), "pthread_join");
        printf("thread %i joined\n", i);
    }

    return EXIT_SUCCESS;
}

void *timer_begin_new_day(void *data) {
    int *id = (int *) data;

    pthread_mutex_lock(&day_mutex);
    printf("Timer %d wakes up citizens by broadcasting\n", *id);
    day_has_begun = 1;
    pthread_cond_broadcast(&citizen_can_wake_up_cond);
    pthread_mutex_unlock(&day_mutex);

    return NULL;
}

void *citizen_spends_his_day(void *data) {
    int *id = (int *) data;

    pthread_mutex_lock(&day_mutex);
    printf("The citizen %d is sleeping\n", *id);
    while (!day_has_begun) {
        pthread_cond_wait(&citizen_can_wake_up_cond, &day_mutex);
    }
    printf("The citizen %d woke up\n", *id);
    pthread_mutex_unlock(&day_mutex);

    printf("The citizen %d spends his day...\n", *id);
    /* Doing a lot of things */

    return NULL;
}
src/without_pb_reentrant.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>  /* strerror() */

/**
 * @file without_pb_reentrant.c
 * @see pb_reentrant.c
 *
 * A simple program to show the importance of using "reentrant" functions.
 *
 * f_r() is the reentrant version of f() (as rand_r() is for rand()): the
 * caller provides the state, so there is no hidden static variable any
 * more. Each thread has its own seed: no shared data, no mutex needed.
 * Same seed in every thread: each one displays the first value (16838).
 */

#define THREADS 4

int f_r(unsigned int *next) {
    *next = *next * 1103515245 + 12345;
    return (int) ((*next / 65536) % 32768);
}

void *doit(void *vargp) {
    (void) vargp;  /* Mark it as unused */
    unsigned int seed = 1;  /* private state, in the stack of the thread */
    printf("[%lu]: val = %d\n", (unsigned long) pthread_self(), f_r(&seed));
    return NULL;
}

int main(void) {
    int i;
    int err;
    pthread_t tid[THREADS];

    for (i = 0; i < THREADS; i++) {
        if ((err = pthread_create(&tid[i], NULL, doit, NULL)) != 0) {
            fprintf(stderr, "pthread_create : %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < THREADS; i++) {
        if ((err = pthread_join(tid[i], NULL)) != 0) {
            fprintf(stderr, "pthread_join : %s\n", strerror(err));
            exit(EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}