多线程互斥锁问题(多线程模拟银行存取款)

通过以下代码可以看到互斥锁的重要性:

#include <stdio.h>

#include <unistd.h>
#include <pthread.h>


static int totalmoney = 20000;   //总金额20000


pthread_mutex_t mutex ; //定义变量


int Check_balance()
{
return totalmoney;
}


void Save_money(int samoney)
{
int surplus;
while(1)
{
//pthread_mutex_lock( &mutex ) ; //@a1,锁定mutex指向的互斥锁
surplus = Check_balance();
sleep(1);

totalmoney = surplus + samoney;
printf("After save money current balance is %d\n",totalmoney);
//pthread_mutex_unlock( &mutex ) ; //@a1,给mutex指向的互斥锁解锁
sleep(1);
}
}


void Draw_money(int gemoney)
{
while(1)
{
//pthread_mutex_lock( &mutex ) ; //@a2,锁定mutex指向的互斥锁

totalmoney = totalmoney - gemoney;
printf("After draw money current balance is %d\n",totalmoney);
sleep(1);

//pthread_mutex_unlock( &mutex ) ; //@a2,给mutex指向的互斥锁解锁
}
}


int main()
{
pthread_t thread1,thread2;
int ret1,ret2;
int samoney = 5000;   //存款金额
int gemoney = 10000;   //取款金额

pthread_mutex_init( &mutex , NULL ) ;  //初始化互斥锁

printf("Total money in the account is %d\n\n",totalmoney);
ret1 = pthread_create(&thread1,NULL,(void *)Save_money,(void *)samoney);
if(ret1)
{
fprintf(stdout,"Create thread failed!\n");
return -1;
}
sleep(2);
ret2 = pthread_create(&thread2,NULL,(void *)Draw_money,(void *)gemoney);

if(ret2)
{
fprintf(stdout,"Create thread failed!\n");
return -1;
}

sleep(4);
return 0;

}

取消@a1、@a2处的互斥锁(即不使用互斥锁)时其中又一次的结果如下:

Total money in the account is 20000


After save money current balance is 25000
After draw money current balance is 15000
After save money current balance is 20000
After draw money current balance is 10000
After draw money current balance is 0
After save money current balance is 15000
After draw money current balance is 5000


Total money in the account is 5000

总共存了3次(共15000),取了4次(共40000),这样就只赚(赚了10000)不赔了,要是银行都这样就好了,呵呵~~~


在@a1、@a2处加上互斥锁(即使用互斥锁)时其中又一次的结果如下:

Total money in the account is 20000


After save money current balance is 25000
After draw money current balance is 15000
After save money current balance is 20000
After draw money current balance is 10000


Total money in the account is 10000

总共存了2次(共10000),取了2次(共20000),这样就谁都不会亏了~~~


互斥锁解决了线程不同步问题


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值