linux多线程访问共享资源,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值