线程间的读写锁

xiaoxiao2021-02-28  84

共享独占:

读取锁——共享

写入锁——独占

即:读锁可以加多个;有写锁时,读写锁都加不上;有读锁时,可以加读锁而不能加写锁。

静态分配读写锁:

pthread_rwlock_t  rwlock = PTHREAD_RWLOCK_INITIALIZER;

动态分配读写锁:

pthread_rwlock_init(&rwlock,NULL); pthread_rwlock_destroy(&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 <pthread.h> #include <time.h> pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; int count = 10000; int put_cur = 0; void* search(void* arg){ pthread_rwlock_rdlock(&rwlock); printf("%d leave %d\n",(int)arg,count); // usleep(500000); pthread_rwlock_unlock(&rwlock); } void rollback(void* arg){ count -= put_cur; printf("rollback %d to %d\n",put_cur,count); pthread_rwlock_unlock(&rwlock); } void* put(void* arg){ pthread_cleanup_push(rollback,NULL); pthread_rwlock_wrlock(&rwlock); put_cur = rand()00; count += put_cur; printf("%d put %d ok,leave %d\n",(int)arg,put_cur,count); // usleep(500000); pthread_rwlock_unlock(&rwlock); pthread_cleanup_pop(0); } void* hacker(void* arg){ sleep(2); pthread_t* ptids = arg; pthread_cancel(ptids[0]); printf("\033[41;34mcancel %lu\033[0m\n",ptids[0]); } void* get(void* arg){ pthread_rwlock_wrlock(&rwlock); int cur = rand()00; if(count>cur){ count -= cur; printf("%d crash %d leave %d\n",(int)arg,cur,count); }else{ printf("%d leave not enought %d\n",(int)arg,count); } // usleep(500000); pthread_rwlock_unlock(&rwlock); } int main(){ pthread_t tids[100]; typedef void*(*func_t)(void*); func_t func_arr[3] = {put,search,get}; func_t funcs[100]; pthread_setconcurrency(4); int i=0; srand(time(NULL)); for(i=0;i<100;i++){ funcs[i] = func_arr[rand()%3]; } for(i=0;i<100;i++){ pthread_create(&tids[i],NULL,funcs[i],i); } for(i=0;i<100;i++){ pthread_join(tids[i],NULL); } }
转载请注明原文地址: https://www.6miu.com/read-74072.html

最新回复(0)