Linux多线程(七)读写锁

xiaoxiao2021-02-28  45

读写锁特点: 1)多个读者可以同时进行读 2)写者必须互斥(只允许一个写者写,也不能读者写者同时进行) 3)写者优先于读者(一旦有写者,则后续读者必须等待,唤醒时优先考虑写者) 互斥锁特点:

  一次只能一个线程拥有互斥锁,其他线程只有等待

源码如下:在这个例程中,运行结果和之前的互斥锁一样,下一文会讲述上读锁和写锁的区别

account.h

#ifndef __ACCOUNT_H__#define __ACCOUNT_H__#include <pthread.h>typedef struct{   int code;   double balance;   pthread_rwlock_t m_rw_lock;}Account;extern Account * create_account(int code,double balance);extern void destroy_account(Account *a);extern double with_draw(Account *a,double amt);extern double depoist(Account *a,double amt);extern double get_balance(Account *a);

#endif

account.c

#include "account.h"#include <assert.h>#include <malloc.h>#include <string.h>Account *create_account(int code, double balance){   Account *r=(Account *)malloc(sizeof(Account));   assert(r!=NULL);   r->code=code;   r->balance=balance;   pthread_rwlock_init(&r->m_rw_lock,NULL);   return r;}void destroy_account(Account *a){   assert(a!=NULL);   pthread_rwlock_destroy(&a->m_rw_lock);   free(a);}double with_draw(Account *a, double amt){   assert(a!=NULL);   pthread_rwlock_wrlock(&a->m_rw_lock);   if(amt > a->balance || amt<0){      pthread_rwlock_unlock(&a->m_rw_lock);      return 0.0;   }   double balance=a->balance;   sleep(1);

   balance = balance - amt;

   a->balance = balance;   pthread_rwlock_unlock(&a->m_rw_lock);   return amt;}double depoist(Account *a, double amt){   assert(a!=NULL);   if(amt<0){      return 0.0;   }   pthread_rwlock_wrlock(&a->m_rw_lock);   double balance=a->balance;   sleep(1);   balance = balance + amt;   a->balance = balance;   pthread_rwlock_unlock(&a->m_rw_lock);   return amt;}

转载请注明原文地址: https://www.6miu.com/read-2628714.html

最新回复(0)