企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 读写锁 - 读写锁是一种**特殊的自旋锁** - 允许多个读者同时访问资源以提高读性能 - 对于写操作则是互斥的 提供的api ``` pthread_rwlock_t pthread_rwlock_rdlock(读锁) pthread_rwlock_wrlock(写锁) ``` <details> <summary>main.cpp</summary> ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <vector> pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; int num =0; void *reader(void*){ int times = 100000; while(times--){ pthread_rwlock_rdlock(&rwlock); if (times % 1000==0){ printf("print num in reader:num%d\n", num); usleep(10); } pthread_rwlock_unlock(&rwlock) } } void *writer(void*){ int times = 100000; while(times--){ pthread_rwlock_wrlock(&rwlock); num++; pthread_rwlock_unlock(&rwlock); } } int main(){ printf("stat in main function."); pthread_t thread1,thread2,thread3; pthread_create(&thread1,NULL,&reader,NULL); pthread_create(&thread2,NULL,&reader,NULL); pthread_create(&thread3,NULL,&writer,NULL); pthread_join(thread1,NULL); pthread_join(thread2,NULL); printf("print in main function:num=%d",num); return 0; } ``` </details> <br />