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
#include "mysem.h"
13
14
Semaphore *make_semaphore(int value)
15
{
16
Semaphore *semaphore = check_malloc(sizeof(Semaphore));
17
semaphore->value = value;
18
semaphore->wakeups = 0;
19
semaphore->mutex = make_mutex();
20
semaphore->cond = make_cond();
21
return semaphore;
22
}
23
24
void semaphore_wait(Semaphore *semaphore)
25
{
26
mutex_lock(semaphore->mutex);
27
semaphore->value--;
28
29
if (semaphore->value < 0) {
30
do {
31
cond_wait(semaphore->cond, semaphore->mutex);
32
} while (semaphore->wakeups < 1);
33
semaphore->wakeups--;
34
}
35
mutex_unlock(semaphore->mutex);
36
}
37
38
void semaphore_signal(Semaphore *semaphore)
39
{
40
mutex_lock(semaphore->mutex);
41
semaphore->value++;
42
43
if (semaphore->value <= 0) {
44
semaphore->wakeups++;
45
cond_signal(semaphore->cond);
46
}
47
mutex_unlock(semaphore->mutex);
48
}
49
50