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

时间:2013-09-21 00:01:44

标签: c pthreads mutex

我想重现使用两个修改threads的{​​{1}}时应该遇到的问题。 global variable: solde递增first threadsolde递减它。

源代码更清晰:

second

我得到的有时是:
   #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以初始值250开始):

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

P.S:当我使用[final] solde = 220互斥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

1 个答案:

答案 0 :(得分:1)

更改您的线程函数,使其保留数据的本地副本,并在获取副本后让另一个线程运行。这将突出您正在寻找的问题:

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;
}