Linux多线程(五)多线程访问共享资源

实验:创建两条线程,线程的执行函数是取钱,(本实验有3个文件,其中account.c 和 account.h 文件是模拟银行取钱,存钱,查询余额的函数,test.c为主函数。由于账户里有10000元,两个人去取钱,结果同时取到了10000元

源码如下:

account.c

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

}

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


double get_balance(Account *a){
   double balance = 0.0;
   balance=a->balance;
   return balance;

}


account.h

#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
typedef struct
{
   int code;
   double balance;
}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

test.c

#include
#include
#include
#include
#include
#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;

}

程序运行结果:

   woman(0x7fe943c15700) withdraw 10000.000000 from account 1001
     man(0x7fe944416700) withdraw 10000.000000 from account 1001
the rest of the count is 0.000000
7fe944c19700 thread finished

你可能感兴趣的:(Linux多线程(五)多线程访问共享资源)