读写锁是一把锁
/*读写锁的类型 pthread_rwlock_tpthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);int pthread_rwlock_destory(pthread_rwlock_t *rwlock);int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
*/#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>int num = 1;
pthread_rwlock_t rwlock;
void* writeNum(void * arg) {while(1) {pthread_rwlock_wrlock(&rwlock);num++;printf("++write, tid: %ld, num:%d\n", pthread_self(), num);pthread_rwlock_unlock(&rwlock);usleep(500); }
}
void* readNum(void * arg) {while(1) {pthread_rwlock_rdlock(&rwlock);printf("==read, tid: %ld, num:%d\n", pthread_self(), num);pthread_rwlock_unlock(&rwlock);usleep(500); }
}int main() {pthread_rwlock_init(&rwlock, NULL);pthread_t wtid[3];pthread_t rtid[5];for(int i = 0; i < 3; i++) {pthread_create(&wtid[i], NULL, writeNum, NULL);}for(int i = 0; i < 5; i++) {pthread_create(&rtid[i], NULL, readNum, NULL);}for(int i = 0; i < 3; i++) {pthread_detach(wtid[i]);}for(int i = 0; i < 5; i++) {pthread_detach(rtid[i]);}pthread_exit(NULL);pthread_rwlock_destroy(&rwlock);return 0;}