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 2015 Allen Downey
4
License: Creative Commons Attribution-ShareAlike 3.0
5
6
*/
7
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <pthread.h>
11
#include "utils.h"
12
13
// UTILITY CODE
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) perror_exit("malloc failed");
25
return p;
26
}
27
28
// MUTEX WRAPPER
29
30
Mutex *make_mutex()
31
{
32
Mutex *mutex = check_malloc(sizeof(Mutex));
33
int n = pthread_mutex_init(mutex, NULL);
34
if (n != 0) perror_exit("make_lock failed");
35
return mutex;
36
}
37
38
void mutex_lock(Mutex *mutex)
39
{
40
int n = pthread_mutex_lock(mutex);
41
if (n != 0) perror_exit("lock failed");
42
}
43
44
void mutex_unlock(Mutex *mutex)
45
{
46
int n = pthread_mutex_unlock(mutex);
47
if (n != 0) perror_exit("unlock failed");
48
}
49
50
// COND WRAPPER
51
52
Cond *make_cond()
53
{
54
Cond *cond = check_malloc(sizeof(Cond));
55
int n = pthread_cond_init(cond, NULL);
56
if (n != 0) perror_exit("make_cond failed");
57
58
return cond;
59
}
60
61
void cond_wait(Cond *cond, Mutex *mutex)
62
{
63
int n = pthread_cond_wait(cond, mutex);
64
if (n != 0) perror_exit("cond_wait failed");
65
}
66
67
void cond_signal(Cond *cond)
68
{
69
int n = pthread_cond_signal(cond);
70
if (n != 0) perror_exit("cond_signal failed");
71
}
72
73
74