Linux多线程(十一)信号量实现互斥锁

这份代码是在之前介绍的互斥锁的代码上直接改过来的,可以对比看看

account.h:

#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include <pthread.h>
#include <semaphore.h>
typedef struct
{
   int code;
   double balance;
   sem_t sem;
}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;
   sem_init(&r->sem,0,1);
   return r;
}
void destroy_account(Account *a)
{  
   assert(a!=NULL);
   sem_destroy(&a->sem);
   free(a);
}
double with_draw(Account *a, double amt)
{  
   assert(a!=NULL);
   sem_wait(&a->sem);
   if(amt > a->balance || amt<0){
     sem_post(&a->sem);
     return 0.0;
   }
   double balance=a->balance;
   sleep(1); 

   balance = balance - amt;

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

}

test.c:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "account.h"
typedef struct
{
   char name[20];
   Account *account;
   double amt;
}Arg;


void *func_th(void *arg)
{
    Arg *r=(Arg *)arg;
    double amt=with_draw(r->account,r->amt);
    printf("%8s(0x%lx) withdraw %f from account %d\n",
                  r->name,pthread_self(),amt,r->account->code);
    return (void*)0;
}
int main(int argc,char *argv[])
{
    int err;
    pthread_t boy,girl;
    Account *a=create_account(1001,10000);
    Arg r1,r2;
    strcpy(r1.name,"man");
    r1.account=a;
    r1.amt=10000;

    strcpy(r2.name,"woman");

    r2.account=a;
    r2.amt=10000;
    if((err=pthread_create(&boy,NULL,func_th,(void *)&r1))!=0)
    {
        perror("pthread create error");
    }
    if((err=pthread_create(&girl,NULL,func_th,(void *)&r2))!=0)
    {
        perror("pthread create error");
    }


    pthread_join(boy,NULL);
    pthread_join(girl,NULL);


    //打印余额
   printf("the rest of the count is %f\n",get_balance(a));
   //打印线程ID
   printf("%lx thread finished\n",pthread_self());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38211852/article/details/80405391