C语言多线程程序:模拟银行账户取款
C语言多线程程序:模拟银行账户取款
本示例使用C语言多线程模拟银行账户取款,演示如何使用pthread库创建线程、传递参数以及实现同步操作。代码通过两个线程模拟取款操作,每个线程从账户中取款特定金额。
原始代码:
/* twordcount1.c - threaded word counter for two files. Version 1 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
void* add_count();
void* sub_count();
int total_words ;
int num=0;
int main(int ac, char *av[])
{
pthread_t t1, t2; /* two threads */
total_words =100;
printf("my bank account has %d yuan\n", total_words);
pthread_create(&t1, NULL, add_count, NULL);
pthread_create(&t2, NULL, add_count, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("my account has left %d yuan\n", total_words);
return 0;
}
void* add_count()
{
int temp;
int temp2=0;
temp = total_words;
num++;
for(int i=0; i<65432; i++){
for(int j=0; j<10; j++){
;
}
}
if(temp>=60){
temp=temp-60;
printf("%d: withdraw %d yuan from my bank account\n", num,60);
}else{
temp2=temp;
temp=0;
printf("%d: withdraw %d yuan from my bank account\n", num, temp2);
}
total_words=temp;
return NULL;
}
void* sub_count()
{
total_words--;
return NULL;
}
修改后的代码:
/* twordcount1.c - threaded word counter for two files. Version 1 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <ctype.h>
void* add_count();
void* sub_count();
int total_words ;
int num=0;
int main(int ac, char *av[])
{
pthread_t t1, t2; /* two threads */
total_words =100;
printf("my bank account has %d yuan\n", total_words);
pthread_create(&t1, NULL, add_count, (void*)60); // 传入参数60
pthread_create(&t2, NULL, add_count, (void*)40); // 传入参数40
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("my account has left %d yuan\n", total_words);
return 0;
}
void* add_count(void* arg) // 接收参数
{
int temp;
int temp2=0;
temp = total_words;
num++;
for(int i=0; i<65432; i++){
for(int j=0; j<10; j++){
;
}
}
int withdraw = (int)arg; // 将参数转换为整型
if(temp>=withdraw){
temp=temp-withdraw;
printf("%d: withdraw %d yuan from my bank account\n", num, withdraw);
}else{
temp2=temp;
temp=0;
printf("%d: withdraw %d yuan from my bank account\n", num, temp2);
}
total_words=temp;
return NULL;
}
void* sub_count()
{
total_words--;
return NULL;
}
代码修改说明:
- 在
main函数中,使用pthread_create创建线程时,将取款金额作为参数传递给add_count函数。 - 在
add_count函数中,使用(int)arg将传入的参数转换为整型,并将该值作为取款金额。
运行结果:
my bank account has 100 yuan
1: withdraw 60 yuan from my bank account
2: withdraw 40 yuan from my bank account
my account has left 0 yuan
总结:
本示例演示了如何在C语言多线程程序中传递参数,以及如何使用参数控制线程的行为。代码使用 pthread 库创建线程,并使用 pthread_create 函数将取款金额作为参数传递给线程函数。线程函数使用 (int)arg 将传入的参数转换为整型,并使用该值作为取款金额。最后,程序使用 pthread_join 函数等待线程完成。
注意:
本示例仅供参考,实际应用中需要考虑并发访问共享资源的问题,并使用同步机制来确保数据的一致性。
原文地址: https://www.cveoy.top/t/topic/oj6E 著作权归作者所有。请勿转载和采集!