Concurrency 我想使用Peterson代码来防止出现竞争情况
我不知道Peterson解决方案,但我想使用Peterson解决方案来运行代码。Concurrency 我想使用Peterson代码来防止出现竞争情况,concurrency,pthreads,Concurrency,Pthreads,我不知道Peterson解决方案,但我想使用Peterson解决方案来运行代码。 我还想知道彼得森的解决方案 #include <stdio.h> #include <pthread.h> int money=1000; void func1(void); void func2(void); int main(void) { pthread_t id1; pthread_t id2; int tret; printf("I'm
我还想知道彼得森的解决方案
#include <stdio.h>
#include <pthread.h>
int money=1000;
void func1(void);
void func2(void);
int main(void)
{
pthread_t id1;
pthread_t id2;
int tret;
printf("I'm main thread\n");
pthread_create(&id1, NULL, func1, NULL);
pthread_create(&id2, NULL, func2, NULL);
pthread_join(id1, &tret);
pthread_join(id2, &tret);
printf("money: %d\n", money);
}
void func1(void){
int i;
for(i=0; i<100; i++){
deposit(10);
withdraw(10);
}
}
void func2(void){
int i;
for(i=0; i<100; i++){
deposit(10);
withdraw(10);
}
}
int withdraw(amount){
int balance;
balance = get_balance();
balance = balance - amount;
put_balance(balance);
return balance;
}
int deposit(amount){
int balance;
balance = get_balance();
balance = balance + amount;
put_balance(balance);
return balance;
}
int get_balance(void)
{
return money;
}
void put_balance(int balance)
{
money = balance;
}
#包括
#包括
整数货币=1000;
无效1(无效);
无效2(无效);
内部主(空)
{
pthread_t id1;
pthread_t id2;
int tret;
printf(“我是主线程”\n);
pthread_create(&id1,NULL,func1,NULL);
pthread_create(&id2,NULL,func2,NULL);
pthread_join(id1和tret);
pthread_join(id2和tret);
printf(“货币:%d\n”,货币);
}
无效功能1(无效){
int i;
对于(i=0;i)(如果您在int中使用return money=balance;
) 放置_balance()
,您可以实现int deposit()
返回put\u balance(get\u balance()+amount);
)至于它的编码是否正确,不,给出的代码不正确,因为它有数据竞争。根本没有任何同步的迹象,无论是通过Petersen算法还是通过任何其他同步方法。我认为您指的是。