📚 The CoCalc Library - books, templates and other resources
License: OTHER
/* Example code for Think OS.12Copyright 2015 Allen Downey3License: Creative Commons Attribution-ShareAlike 3.045*/67#include <stdio.h>8#include <stdlib.h>9#include <pthread.h>10#include "utils.h"1112// UTILITY CODE1314void perror_exit(char *s)15{16perror(s);17exit(-1);18}1920void *check_malloc(int size)21{22void *p = malloc(size);23if (p == NULL) perror_exit("malloc failed");24return p;25}2627// MUTEX WRAPPER2829Mutex *make_mutex()30{31Mutex *mutex = check_malloc(sizeof(Mutex));32int n = pthread_mutex_init(mutex, NULL);33if (n != 0) perror_exit("make_lock failed");34return mutex;35}3637void mutex_lock(Mutex *mutex)38{39int n = pthread_mutex_lock(mutex);40if (n != 0) perror_exit("lock failed");41}4243void mutex_unlock(Mutex *mutex)44{45int n = pthread_mutex_unlock(mutex);46if (n != 0) perror_exit("unlock failed");47}4849// COND WRAPPER5051Cond *make_cond()52{53Cond *cond = check_malloc(sizeof(Cond));54int n = pthread_cond_init(cond, NULL);55if (n != 0) perror_exit("make_cond failed");5657return cond;58}5960void cond_wait(Cond *cond, Mutex *mutex)61{62int n = pthread_cond_wait(cond, mutex);63if (n != 0) perror_exit("cond_wait failed");64}6566void cond_signal(Cond *cond)67{68int n = pthread_cond_signal(cond);69if (n != 0) perror_exit("cond_signal failed");70}71727374