#include #include #include #include pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; int num_readers = 0; int num_writers = 0; void *reader (int p) { while (1) { printf("Reader %d ready\n", p); pthread_rwlock_rdlock(&rwlock); num_readers++; printf("Reader %d started (num. readers = %d)\n", p, num_readers); usleep(2000000); num_readers--; printf("Reader %d finished (num. readers = %d)\n", p, num_readers); pthread_rwlock_unlock(&rwlock); usleep(1000000 * p); } } void *writer (int p) { while (1) { printf("Writer %d ready\n", p); pthread_rwlock_wrlock(&rwlock); num_writers++; printf("Writer %d started (num. writers = %d)\n", p, num_writers); usleep(1000000); num_writers--; printf("Writer %d finished (num. writers = %d)\n", p, num_writers); pthread_rwlock_unlock(&rwlock); usleep(1000000 * p * 5); } } int main () { pthread_t thr_id; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&thr_id, &attr, reader, (void *) 1); pthread_create(&thr_id, &attr, reader, (void *) 2); pthread_create(&thr_id, &attr, reader, (void *) 3); pthread_create(&thr_id, &attr, reader, (void *) 4); pthread_create(&thr_id, &attr, reader, (void *) 5); pthread_create(&thr_id, &attr, writer, (void *) 1); pthread_create(&thr_id, &attr, writer, (void *) 2); usleep(50000000); //simulation time return 0; }