【发布时间】:2021-07-18 17:59:06
【问题描述】:
使用 pthread 库编写一个小的 C 代码。我对这个代码的要求是先存钱再提钱。
#include <stdio.h>
#include <pthread.h>
int counter = 0;
void *increase();
void *decrease();
int balance = 500;
void *deposit(void*);
void *withdraw(void*);
int main() {
pthread_t t_inc, t_dec;
int dep_money = 300;
int wd_money = 100;
pthread_create(&t_inc, NULL, deposit, &dep_money);
pthread_create(&t_dec, NULL, withdraw, &wd_money);
// Wait until the thread is finished
pthread_join(t_inc, NULL);
pthread_join(t_dec, NULL);
}
return 0;
}
// Functions for thread
void *deposit(void *args) {
int *money = (int *)args;
balance += *money;
printf("Deposit: New balance: %d\n", balance);
return NULL;
}
void *withdraw(void *args) {
int *money = (int *)args;
if (balance < *money) {
printf("Not enough balance\n");
} else {
balance -= *money;
printf("Withdraw: New balance: %d\n", balance);
}
return NULL;
}
我在 2 个不同的操作系统上使用了这个代码,Ubuntu 和 macOS。由于某种原因,我得到了 2 个不同的结果。
对于 macOS:
存款:新余额:800
提现:新余额:700
对于 Ubuntu:
提现:新余额:400
存款:新余额:700
但是当我在 Ubuntu 中更改 pthread_join() 的顺序时,它按照我想要的顺序运行。
pthread_create(&t_inc, NULL, deposit, &dep_money);
pthread_join(t_inc, NULL);
pthread_create(&t_dec, NULL, withdraw, &w_money);
pthread_join(t_dec, NULL);
总之,我的问题是为什么在 Ubuntu 中运行的第一个代码中它没有作为 pthread_join(t_inc, NULL); 的第一顺序运行。然后是第二个 pthread_join(t_dec, NULL);相反,它运行相反?而且我必须在 pthread_create() 之后立即调用 pthread_join() 才能让它按顺序工作,因为我还没有创建第二个线程,所以我认为它效率不高。
【问题讨论】:
-
在我看来这只是一个竞争条件,与您使用的操作系统无关。
-
创建两个线程只是为了完成两个不能重叠的工作,这怎么能有效率呢?使用一个线程而不是三个线程不是更有效吗?
标签: c ubuntu pthreads pthread-join