一次只能一个线程拥有互斥锁,其他线程只有等待
源码如下:在这个例程中,运行结果和之前的互斥锁一样,下一文会讲述上读锁和写锁的区别
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;}
