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

来源:互联网 发布: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),这样就谁都不会亏了~~~


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