读写锁的特点
读的时候不可以写 可以读
写的时候不可以读
读写锁写的优先级高
代码环境
Ubuntu18.04+vscode C标准gnu11
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int num = 1;
pthread_rwlock_t rwlock;
void * writeNum(void * arg) {
while(num<50) {
pthread_rwlock_wrlock(&rwlock);
if(num<50){
++num;
printf("++write, tid : %ld, num : %d\n", pthread_self(), num);
}else{
pthread_rwlock_unlock(&rwlock);
break;
}
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
void * readNum(void * arg) {
while(num<50) {
pthread_rwlock_rdlock(&rwlock);
if(num<50){
printf("===read, tid : %ld, num : %d\n", pthread_self(), num);
}else{
pthread_rwlock_unlock(&rwlock);
break;
}
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
int main() {
pthread_rwlock_init(&rwlock, NULL);
pthread_t wtids[3], rtids[5];
for(int i = 0; i < 3; i++) {
pthread_create(&wtids[i],NULL,writeNum,NULL);
}
for(int i = 0; i < 5; i++) {
pthread_create(&rtids[i], NULL, readNum, NULL);
}
for(int i = 0; i < 3; i++) {
pthread_detach(wtids[i]);
}
for(int i = 0; i < 5; i++) {
pthread_detach(rtids[i]);
}
pthread_exit(NULL);
printf("main thread end!\n");
pthread_rwlock_destroy(&rwlock);
return 0;
}
|