#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
#define NUM_INCREMENTS 1000000
static int total = 0;
static pthread_mutex_t total_mutex;
static void* Count(void* unused) {
(void) unused;
for (int index = 0; index < NUM_INCREMENTS; index++) {
pthread_mutex_lock(&total_mutex);
total++;
pthread_mutex_unlock(&total_mutex);
}
return NULL;
}
int main(void) {
pthread_t threads[NUM_THREADS];
if (pthread_mutex_init(&total_mutex, NULL) != 0) {
return EXIT_FAILURE;
}
for (int index = 0; index < NUM_THREADS; index++) {
if (pthread_create(&threads[index], NULL, Count, NULL) != 0) {
return EXIT_FAILURE;
}
}
for (int index = 0; index < NUM_THREADS; index++) {
pthread_join(threads[index], NULL);
}
printf("Expected: %d\n", NUM_THREADS * NUM_INCREMENTS);
printf("Actual: %d\n", total);
pthread_mutex_destroy(&total_mutex);
return EXIT_SUCCESS;
}