#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#define NUM_READERS 5
#define NUM_WRITERS 2
#define NUM_ITERATIONS 10
static const char *reader_names[] = {
"Robin", "Riley", "Raven", "Reese", "Renee",
"Reena", "River", "Rohan", "Ronan", "Rania"
};
static const char *writer_names[] = {
"Wendy", "Wayne", "Wyatt", "Wilma", "Wylie",
"Wanda", "Wells", "Warda", "Woody", "Walid",
};
struct shared_data {
int value;
};
struct shared_data data;
void *
reader(void *arg)
{
const char *id = (char *) arg;
for (int i = 0; i < NUM_ITERATIONS; i++) {
int read_value = __atomic_load_n(&data.value, __ATOMIC_SEQ_CST);
printf("Reader %s reads value: %d\n", id,
read_value);
usleep(10000 + rand() % 90000); // Sleep for 10-100ms
}
return NULL;
}
void *
writer(void *arg)
{
const char *id = (char *) arg;
for (int i = 0; i < NUM_ITERATIONS; i++) {
int updated_value = __atomic_add_fetch(&data.value, 1, __ATOMIC_SEQ_CST);
printf("Writer %s updates value to: %d\n", id,
updated_value);
usleep(10000 + rand() % 90000); // Sleep for 10-100ms
}
return NULL;
}
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
int
main(void)
{
assert(ARRAY_SIZE(reader_names) >= NUM_READERS);
assert(ARRAY_SIZE(writer_names) >= NUM_WRITERS);
pthread_t readers[NUM_READERS];
pthread_t writers[NUM_WRITERS];
__atomic_store_n(&data.value, 0, __ATOMIC_SEQ_CST);
// Create reader threads
for (int i = 0; i < NUM_READERS; i++) {
if (pthread_create(&readers[i], NULL, reader,
(void *) reader_names[i]) != 0) {
fprintf(stderr, "Failed to create reader thread\n");
return 1;
}
}
// Create writer threads
for (int i = 0; i < NUM_WRITERS; i++) {
if (pthread_create(&writers[i], NULL, writer,
(void *) writer_names[i]) != 0) {
fprintf(stderr, "Failed to create writer thread\n");
return 1;
}
}
// Wait for all threads to complete
for (int i = 0; i < NUM_READERS; i++) {
pthread_join(readers[i], NULL);
}
for (int i = 0; i < NUM_WRITERS; i++) {
pthread_join(writers[i], NULL);
}
int final_value = __atomic_load_n(&data.value, __ATOMIC_SEQ_CST);
printf("Final value: %d\n", final_value);
return 0;
}