Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
/* Example code for Think OS.
2
3
Copyright 2014 Allen Downey
4
License: GNU GPLv3
5
6
*/
7
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <pthread.h>
11
#include "mutex.h"
12
13
#define NUM_CHILDREN 5
14
15
void perror_exit(char *s)
16
{
17
perror(s);
18
exit(-1);
19
}
20
21
void *check_malloc(int size)
22
{
23
void *p = malloc(size);
24
if (p == NULL) {
25
perror_exit("malloc failed");
26
}
27
return p;
28
}
29
30
typedef struct {
31
int counter;
32
Mutex *mutex;
33
} Shared;
34
35
Shared *make_shared(int end)
36
{
37
Shared *shared = check_malloc(sizeof(Shared));
38
shared->counter = 0;
39
shared->mutex = make_mutex();
40
return shared;
41
}
42
43
pthread_t make_thread(void *(*entry)(void *), Shared *shared)
44
{
45
int ret;
46
pthread_t thread;
47
48
ret = pthread_create(&thread, NULL, entry, (void *) shared);
49
if (ret != 0) {
50
perror_exit("pthread_create failed");
51
}
52
return thread;
53
}
54
55
void join_thread(pthread_t thread)
56
{
57
int ret = pthread_join(thread, NULL);
58
if (ret == -1) {
59
perror_exit("pthread_join failed");
60
}
61
}
62
63
void child_code(Shared *shared)
64
{
65
mutex_lock(shared->mutex);
66
printf("counter = %d\n", shared->counter);
67
shared->counter++;
68
mutex_unlock(shared->mutex);
69
}
70
71
void *entry(void *arg)
72
{
73
Shared *shared = (Shared *) arg;
74
child_code(shared);
75
pthread_exit(NULL);
76
}
77
78
int main()
79
{
80
int i;
81
pthread_t child[NUM_CHILDREN];
82
83
Shared *shared = make_shared(1000000);
84
85
for (i=0; i<NUM_CHILDREN; i++) {
86
child[i] = make_thread(entry, shared);
87
}
88
89
for (i=0; i<NUM_CHILDREN; i++) {
90
join_thread(child[i]);
91
}
92
93
return 0;
94
}
95
96