Newer
Older
/*
* SPDX-FileCopyrightText: 2018 Bruce Cowan <bruce@bcowan.me.uk>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#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;
}