#include <pthread.h> #include <stdio.h> #include <unistd.h> void readFunc(); void writeFunc(); int data = 0; pthread_rwlock_t rwlock; int main() { pthread_rwlock_init(&rwlock, NULL); pthread_t readThread; pthread_t writeThread; pthread_t readThread1; pthread_create(&readThread, NULL, readFunc, NULL); pthread_create(&writeThread, NULL, writeFunc, NULL); pthread_create(&readThread1, NULL, readFunc, NULL); pthread_join(readThread, NULL); pthread_join(writeThread, NULL); pthread_join(readThread1, NULL); pthread_rwlock_destroy(&rwlock); return 0; } void readFunc() { while (1) { pthread_rwlock_rdlock(&rwlock); printf("read data:%d, tid:%d ", data, pthread_self()); sleep(1); pthread_rwlock_unlock(&rwlock); } } void writeFunc() { while (1) { pthread_rwlock_wrlock(&rwlock); printf("write data:%d, tid:%d ", data, pthread_self()); data++; sleep(2); pthread_rwlock_unlock(&rwlock); } }