gpt4 book ai didi

C - 使用 pthread 重现两个线程之间全局变量的同步问题

转载 作者:行者123 更新时间:2023-11-30 15:45:39 25 4
gpt4 key购买 nike

我想重现使用两个 threads 时应该遇到的问题修改 global variable: soldefirst thread增加 soldesecond减少它。

有源代码就更清楚了:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

int solde = 250;

void *threadFunc(void *arg)
{
if (strcmp(arg, "credit") == 0)
{
// increment critical ressource
printf("[credit-start] solde = %d\n", solde);
solde = solde + 10000;
printf("[credit-end] solde = %d\n", solde);
} else {
// decrement critical ressource
printf("[debit-start] solde = %d\n", solde);
solde = solde - 30;
printf("[debit-end] solde = %d\n", solde);
}

return NULL;
}

int main()
{
// spawn a thread
pthread_t threadCredit;
pthread_t threadDebit;

int i;
for (i = 0; i < 2; i++)
{
if (i == 0)
pthread_create(&threadCredit, NULL, &threadFunc, "credit");
else
pthread_create(&threadDebit, NULL, &threadFunc, "debit");
}

pthread_join(threadCredit, NULL);
pthread_join(threadDebit, NULL);

printf("[final] solde = %d\n", solde);
return 0;
}

我有时得到的是:
[debit-start] solde = 250
[debit-end] solde = 220 (-30)
[credit-start] solde = 250 // <= I wouldnt get this with mutex
[credit-end] solde = 10220 (+10000)
[final] solde = 10220

有时:
[credit-start] solde = 250
[credit-end] solde = 10250 (+10000)
[debit-start] solde = 250 // <= I wouldnt get this with mutex
[debit-end] solde = 10220 (-30)
[final] solde = 10220

但是,我观察到 result即使不使用 mutex 也是正确的。我想要得到的是这样的错误结果(其中两个 threads 以初始值 250 开头):

[credit-start] solde = 250
[credit-end] solde = 10250 (+10000)
[debit-start] solde = 250
[debit-end] solde = 220 (-30)
[final] solde = 220

P.S:当我使用pthread时互斥体around the inner content of线程函数`,结果更有逻辑:

[debit-start] solde = 250
[debit-end] solde = 220
[credit-start] solde = 220
[credit-end] solde = 10220
[final] solde = 10220

或者:

[credit-start] solde = 250
[credit-end] solde = 10250
[debit-start] solde = 10250
[debit-end] solde = 10220
[final] solde = 10220

最佳答案

更改您的线程函数,以便它保留数据的本地副本,并让其他线程在获取副本后运行。这将突出显示您正在寻找的问题:

void *threadFunc(void *arg)
{
int local_solde = solde;
sleep(1);
if (strcmp(arg, "credit") == 0)
{
// increment critical ressource
printf("[credit-start] solde = %d\n", local_solde);
solde = local_solde + 10000;
printf("[credit-end] solde = %d\n", solde);
} else {
// decrement critical ressource
printf("[debit-start] solde = %d\n", local_solde);
solde = local_solde - 30;
printf("[debit-end] solde = %d\n", solde);
}

return NULL;
}

关于C - 使用 pthread 重现两个线程之间全局变量的同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18927523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com