#include #include #include #include #include #include #include #include #include // WARNING: This example does not work, I couldn't figure out why the lock does not work correcly. // The final counter result should not change, but it does. struct shared_data { pthread_mutex_t mutex; int counter; }; void run(const char *name, struct shared_data *data) { for (int i = 0; i < 10000; i++) { if (pthread_mutex_lock(&data->mutex) != 0) { perror("pthread_mutex_lock"); } data->counter++; if (pthread_mutex_unlock(&data->mutex) != 0) { perror("pthread_mutex_unlock"); } } } 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); printf("Counter is %d\n", shared_data->counter); }