Universidad de Costa Rica
Escuela de Ciencias de la Computación e Informática
CI-0117 Programación paralela y concurrente
Prácticas
|
|
|
CI0117 /
Practicas
/ Semana-06 / |
#include <pthread.h>
#include <stdio.h>
#include <unistd.h> // For sleep
#include "RWLock.h"
// Shared data protected by the read-write lock
int shared_data = 0;
// The read-write lock
RWLock rwlock;
// Reader thread function
void *reader_thread(void *arg) {
long id = (long)arg;
for (int i = 0; i < 5; ++i) {
rwlock.RdLock(); // Acquire read lock
printf("Reader %ld: Read shared_data = %d\n", id, shared_data);
rwlock.Unlock(); // Release read lock
sleep(1); // Simulate some work
}
return NULL;
}
// Writer thread function
void *writer_thread(void *arg) {
long id = (long)arg;
for (int i = 0; i < 3; ++i) {
rwlock.WrLock(); // Acquire write lock
shared_data++;
printf("Writer %ld: Wrote shared_data = %d\n", id, shared_data);
rwlock.Unlock(); // Release write lock
sleep(2); // Simulate some work
}
return NULL;
}
int main() {
pthread_t readers[2];
pthread_t writers[1];
// Create reader threads
for (long i = 0; i < 2; ++i) {
pthread_create(&readers[i], NULL, reader_thread, (void *)(i + 1));
}
// Create writer thread
pthread_create(&writers[0], NULL, writer_thread, (void *)1);
// Join threads
for (int i = 0; i < 2; ++i) {
pthread_join(readers[i], NULL);
}
pthread_join(writers[0], NULL);
// Destroy the read-write lock
printf("Main: Final shared_data = %d\n", shared_data);
return 0;
}