#include #include #include #include #include #include #include #include #include // WARNING: This example does not work, I couldn't figure out why the child process goes into a deadlock on `pthread_mutex_lock` struct shared_data { pthread_mutex_t mutex; int counter; }; void milli_sleep(int milliseconds) { struct timespec ts; ts.tv_sec = milliseconds / 1000; ts.tv_nsec = (milliseconds % 1000) * 1000000; nanosleep(&ts, &ts); } float random_float() { return (float)rand()/(float)RAND_MAX; } int random_range(int from, int to) { return random_float()*(to-from) + from; } void run(const char *name, struct shared_data *data) { printf("[%s] started, mutex: %p\n", name, &data->mutex); for (int i = 0; i < 10; i++) { if (pthread_mutex_lock(&data->mutex) != 0) { perror("pthread_mutex_lock"); } int counter = data->counter; milli_sleep(random_range(0, 100)); data->counter = counter + 1; printf("[%s] counter is %d\n", name, counter + 1); if (pthread_mutex_unlock(&data->mutex) != 0) { perror("pthread_mutex_unlock"); } } printf("[%s] finished\n", name); } int main() { struct shared_data *shared_data = mmap(NULL, sizeof(struct shared_data), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (shared_data == NULL) { perror("mmap"); return -1; } if (pthread_mutex_init(&shared_data->mutex, NULL) < 0) { printf("Failed to initialise mutex\n"); return -1; } shared_data->counter = 0; int pid = fork(); if (pid == 0) { srand(time(NULL)+1); run("Child ", shared_data); return 0; } else { srand(time(NULL)+2); run("Parent", shared_data); } int child_status; waitpid(pid, &child_status, 0); }