📚 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>1011#define NUM_CHILDREN 51213void perror_exit(char *s)14{15perror(s);16exit(-1);17}1819void *check_malloc(int size)20{21void *p = malloc(size);22if (p == NULL) {23perror_exit("malloc failed");24}25return p;26}2728typedef struct {29int counter;30} Shared;3132Shared *make_shared(int end)33{34Shared *shared = check_malloc(sizeof(Shared));35shared->counter = 0;36return shared;37}3839pthread_t make_thread(void *(*entry)(void *), Shared *shared)40{41int ret;42pthread_t thread;4344ret = pthread_create(&thread, NULL, entry, (void *) shared);45if (ret != 0) {46perror_exit("pthread_create failed");47}48return thread;49}5051void join_thread(pthread_t thread)52{53int ret = pthread_join(thread, NULL);54if (ret == -1) {55perror_exit("pthread_join failed");56}57}5859void child_code(Shared *shared)60{61printf("counter = %d\n", shared->counter);62shared->counter++;63}6465void *entry(void *arg)66{67Shared *shared = (Shared *) arg;68child_code(shared);69pthread_exit(NULL);70}7172int main()73{74int i;75pthread_t child[NUM_CHILDREN];7677Shared *shared = make_shared(1000000);7879for (i=0; i<NUM_CHILDREN; i++) {80child[i] = make_thread(entry, shared);81}8283for (i=0; i<NUM_CHILDREN; i++) {84join_thread(child[i]);85}8687return 0;88}899091