⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 atm.c

📁 多线程模拟两人同时使用两个自动取款机访问同一共享帐号
💻 C
字号:
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>

#define MAX 10;
pthread_t thread[2];
pthread_mutex_t mut;
int account = 1000;
int deposit_amount = 0;
int withdraw_amount = 0;
int i=10;
void * thread1(void *arg)/*customer1取款*/
{
printf ("customer1: I'm Lucy\n");

while(i)
{
	deposit_amount = (int)(random()%100); 
	pthread_mutex_lock(&mut);
	account = account+deposit_amount;	
	printf("Lucy has deposited %d dollars\n",deposit_amount);
	printf("The balance of the account is %d dollars\n",account);
	i--;
	pthread_mutex_unlock(&mut);
		sleep(2);
}

printf("customer1 :Lucy has finished my tasks\n");
pthread_exit(NULL);
}

void * thread2(void *arg)/*customer2存款*/
{
printf("customer2 : I'm Lily\n");

while (i)
{
withdraw_amount = (int)(random()%100); 
pthread_mutex_lock(&mut);
if(account>=withdraw_amount)
{
account = account-withdraw_amount;
printf("Lily has withdrew %d dollars\n",withdraw_amount);
printf("The balance of the account is %d dollars\n",account);
}
else
{
printf("withdraw failed,balance is not enough!");
printf("The balance of the account is %d dollars",account);
}
i--;
pthread_mutex_unlock(&mut);
sleep(2);

}

printf("customer2 :Lily has finished my tasks\n");
pthread_exit(NULL);
}

void createthread()
{
int temp;
memset(&thread, 0, sizeof(thread));


/*创建线程*/
if((temp = pthread_create(&thread[0], NULL, &thread1, "customer1")) != 0)
printf("线程1创建失败!\n");
else
printf("线程1被创建\n");

if((temp = pthread_create(&thread[1], NULL, &thread2, "customer2")) != 0) 
printf("线程2创建失败");
else
printf("线程2被创建\n");

}

void waitthread()
{
/*等待线程结束*/
	if(thread[0] !=0) {
pthread_join(thread[0],NULL);
printf("线程1已经结束\n");
}
if(thread[1] !=0) {
pthread_join(thread[1],NULL);
printf("线程2已经结束\n");
}
}

int main()
{ 
/*用默认属性初始化互斥锁*/
pthread_mutex_init(&mut,NULL);

printf("creating threads.....\n");
createthread();
printf("running..........\n");
waitthread();

return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -