qfedu-linux-advanced-level/day7/rwlock_2.c

98 lines
2.3 KiB
C
Raw Permalink Normal View History

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
int money = 1000; // 存款余额
int exit_flag = 0; // 退出标志
void *task1(void *data)
{
while (1)
{
pthread_rwlock_wrlock(&rwlock); // 加写锁
// 查询余额
printf("存款任务-余额: %d\n", money);
usleep(200 * 1000);
// 从键盘读取存入的金额
printf("请输入存款金额 (输入 0 结束存款): ");
fflush(stdout);
int m;
scanf("%d", &m);
if (m == 0)
{
exit_flag = 1;
pthread_rwlock_unlock(&rwlock); // 解锁
break;
}
money += m;
// 修改余额并打印结果
printf("存款成功, 余额为 %d\n", money);
pthread_rwlock_unlock(&rwlock); // 解锁
}
pthread_exit(NULL);
}
void *task2(void *data)
{
while (1)
{
pthread_rwlock_wrlock(&rwlock); // 加写锁
// 查询余额
printf("取款任务-余额: %d\n", money);
usleep(200 * 1000);
// 从键盘读取取出的金额
printf("请输入取款金额 (输入 0 结束取款): ");
fflush(stdout);
int m;
scanf("%d", &m);
if (m == 0)
{
exit_flag = 1;
pthread_rwlock_unlock(&rwlock); // 解锁
break;
}
if (money >= m)
{
money -= m;
// 修改余额并打印结果
printf("取款成功, 余额为 %d\n", money);
}
else
{
printf("取款失败, 余额不足\n");
}
pthread_rwlock_unlock(&rwlock); // 解锁
}
pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
while (1)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, task1, NULL);
pthread_create(&t2, NULL, task2, NULL);
while (1)
{
pthread_rwlock_rdlock(&rwlock);
if (exit_flag)
{
pthread_rwlock_unlock(&rwlock);
break;
}
pthread_rwlock_unlock(&rwlock);
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
pthread_rwlock_destroy(&rwlock);
return 0;
}