1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #include <stdio.h> #include <pthread.h>
pthread_rwlock_t rwlock; int shared_data = 0;
void* reader(void* arg) { pthread_rwlock_rdlock(&rwlock); printf("Reader %ld: shared_data = %d\n", (long)arg, shared_data); pthread_rwlock_unlock(&rwlock); return NULL; }
void* writer(void* arg) { pthread_rwlock_wrlock(&rwlock); shared_data++; printf("Writer %ld: shared_data = %d\n", (long)arg); pthread_rwlock_unlock(&rwlock); return NULL; }
int main() { pthread_t readers[5], writers[5]; pthread_rwlock_init(&rwlock, NULL);
for (long i = 0; i < 5; i++) { pthread_create(&readers[i], NULL, reader, (void*)i); } for (long i = 0; i < 5; i++) { pthread_create(&writers[i], NULL, writer, (void*)i); }
for (int i = 0; i < 5; i++) { pthread_join(readers[i], NULL); } for (int i = 0; i < 5; i++) { pthread_join(writers[i], NULL); }
pthread_rwlock_destroy(&rwlock); return 0; }
|