📚 The CoCalc Library - books, templates and other resources
License: OTHER
/* Example code for Think OS.12Copyright 2014 Allen Downey3License: GNU GPLv345*/67#include <stdio.h>8#include <stdlib.h>9#include <pthread.h>10#include "mutex.h"1112#define NUM_CHILDREN 51314void perror_exit(char *s)15{16perror(s);17exit(-1);18}1920void *check_malloc(int size)21{22void *p = malloc(size);23if (p == NULL) {24perror_exit("malloc failed");25}26return p;27}2829typedef struct {30int counter;31Mutex *mutex;32} Shared;3334Shared *make_shared(int end)35{36Shared *shared = check_malloc(sizeof(Shared));37shared->counter = 0;38shared->mutex = make_mutex();39return shared;40}4142pthread_t make_thread(void *(*entry)(void *), Shared *shared)43{44int ret;45pthread_t thread;4647ret = pthread_create(&thread, NULL, entry, (void *) shared);48if (ret != 0) {49perror_exit("pthread_create failed");50}51return thread;52}5354void join_thread(pthread_t thread)55{56int ret = pthread_join(thread, NULL);57if (ret == -1) {58perror_exit("pthread_join failed");59}60}6162void child_code(Shared *shared)63{64mutex_lock(shared->mutex);65printf("counter = %d\n", shared->counter);66shared->counter++;67mutex_unlock(shared->mutex);68}6970void *entry(void *arg)71{72Shared *shared = (Shared *) arg;73child_code(shared);74pthread_exit(NULL);75}7677int main()78{79int i;80pthread_t child[NUM_CHILDREN];8182Shared *shared = make_shared(1000000);8384for (i=0; i<NUM_CHILDREN; i++) {85child[i] = make_thread(entry, shared);86}8788for (i=0; i<NUM_CHILDREN; i++) {89join_thread(child[i]);90}9192return 0;93}949596