Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132929 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 <semaphore.h>
12
#include "utils.h"
13
#include "sem.h"
14
15
// SEMAPHORE WRAPPER
16
17
Semaphore *make_semaphore(int value)
18
{
19
Semaphore *sem = check_malloc(sizeof(Semaphore));
20
int n = sem_init(sem, 0, value);
21
if (n != 0) perror_exit("sem_init failed");
22
return sem;
23
}
24
25
void semaphore_wait(Semaphore *sem)
26
{
27
int n = sem_wait(sem);
28
if (n != 0) perror_exit("sem_wait failed");
29
}
30
31
void semaphore_signal(Semaphore *sem)
32
{
33
int n = sem_post(sem);
34
if (n != 0) perror_exit("sem_post failed");
35
}
36
37
38
39
40