Skip to content
Snippets Groups Projects
thread-incr.c 1.6 KiB
Newer Older
Bruce Cowan's avatar
Bruce Cowan committed
/*
 * SPDX-FileCopyrightText: 2018 Bruce Cowan <bruce@bcowan.me.uk>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

Bruce Cowan's avatar
Bruce Cowan committed
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#include <utils.h>

typedef struct
{
    pthread_t thread;
    int id;
    int loops;
} ThreadData;

static volatile int glob = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

static void
err_exit (const char *func)
{
    fprintf (stderr, "Error: %s\n", func);
}

static void *
thread_func (void *arg)
{
    ThreadData *data = (ThreadData *) arg;

    for (int j = 0; j < data->loops; j++)
    {
        if (pthread_mutex_lock (&mtx))
            err_exit ("pthread_mutex_lock");

        printf ("Thread #%d: glob = %d\n", data->id, glob);

        int loc = glob;
        loc++;
        glob = loc;

        if (pthread_mutex_unlock (&mtx))
            err_exit ("pthread_mutex_unlock");
    }

    return NULL;
}

int
main (int argc, char **argv)
{
    int *loops = get_ints (argc, argv, 1, "Number of loops");

    ThreadData *t1 = malloc (sizeof (ThreadData));
    t1->id = 1;
    t1->loops = *loops;
    if (pthread_create (&t1->thread, NULL, thread_func, t1))
        err_exit ("pthread_create");

    ThreadData *t2 = malloc (sizeof (ThreadData));
    t2->id = 2;
    t2->loops = *loops;
    if (pthread_create (&t2->thread, NULL, thread_func, t2))
        err_exit ("pthread_create");

    if (pthread_join (t1->thread, NULL))
        err_exit ("pthread_join");
    if (pthread_join (t2->thread, NULL))
        err_exit ("pthread_join");

    printf ("End: glob = %d\n", glob);
    
    free (t1);
    free (t2);

    return 0;
}