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
12
#define NUM_CHILDREN 5
13
14
void perror_exit(char *s)
15
{
16
perror(s);
17
exit(-1);
18
}
19
20
void *check_malloc(int size)
21
{
22
void *p = malloc(size);
23
if (p == NULL) {
24
perror_exit("malloc failed");
25
}
26
return p;
27
}
28
29
typedef struct {
30
int counter;
31
} Shared;
32
33
Shared *make_shared(int end)
34
{
35
Shared *shared = check_malloc(sizeof(Shared));
36
shared->counter = 0;
37
return shared;
38
}
39
40
pthread_t make_thread(void *(*entry)(void *), Shared *shared)
41
{
42
int ret;
43
pthread_t thread;
44
45
ret = pthread_create(&thread, NULL, entry, (void *) shared);
46
if (ret != 0) {
47
perror_exit("pthread_create failed");
48
}
49
return thread;
50
}
51
52
void join_thread(pthread_t thread)
53
{
54
int ret = pthread_join(thread, NULL);
55
if (ret == -1) {
56
perror_exit("pthread_join failed");
57
}
58
}
59
60
void child_code(Shared *shared)
61
{
62
printf("counter = %d\n", shared->counter);
63
shared->counter++;
64
}
65
66
void *entry(void *arg)
67
{
68
Shared *shared = (Shared *) arg;
69
child_code(shared);
70
pthread_exit(NULL);
71
}
72
73
int main()
74
{
75
int i;
76
pthread_t child[NUM_CHILDREN];
77
78
Shared *shared = make_shared(1000000);
79
80
for (i=0; i<NUM_CHILDREN; i++) {
81
child[i] = make_thread(entry, shared);
82
}
83
84
for (i=0; i<NUM_CHILDREN; i++) {
85
join_thread(child[i]);
86
}
87
88
return 0;
89
}
90
91