多线程互斥锁问题(多线程模拟银行存取款)
来源:互联网 发布:java继承例子代码 编辑:程序博客网 时间:2024/04/30 21:39
通过以下代码可以看到互斥锁的重要性:
#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),这样就谁都不会亏了~~~
互斥锁解决了线程不同步问题
- 多线程互斥锁问题(多线程模拟银行存取款)
- Java多线程银行存取款程序
- [多线程之一]-NSThread银行取款问题
- Java多线程银行取款
- Axis+Tomcat模拟一个银行存取款
- 接口继承示例:模拟银行存取款
- 模拟银行存取款业务 简要代码
- 用JAVA中的多线程示例银行取款问题
- 用JAVA的多线程实现银行取款的问题
- java模拟多用户取款(多线程同步)
- java多线程问题中简单的存取款实现
- Java-多线程 银行取款小练习
- java 线程同步问题之银行存取款问题
- java 银行存取款模型的线程同步问题
- 银行ATM存取款机
- 银行ATM机存取款
- 银行取款[多线程]{使用同步方法确保线程同步}
- 银行取款[多线程]{使用同步代码块确保线程同步}
- What Why How Hadoop
- office2010卸载不干净无法再安装的问题
- 第四周实验报告
- MP3的C语言调试
- 第四周实验报告1
- 多线程互斥锁问题(多线程模拟银行存取款)
- [ubuntu 10.04 64bit][android]编译时报错:arm-eabi-gcc command not found
- 手机设置的亮度调节功能
- 进程 管理
- 看电影(movie)
- 启动TOGAF9项目之前应遵循的10个步骤
- WAP2.0 XHTML MP
- ural 1031. Railway Tickets | poj 2355
- android gif动画