我想重现使用两个threads
修改global variable: solde
. first thread
递增和递减它 solde
。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
. 我想要得到的是这样的错误结果(两者threads
以初始值 250 开头):
[credit-start] solde = 250
[credit-end] solde = 10250 (+10000)
[debit-start] solde = 250
[debit-end] solde = 220 (-30)
[final] solde = 220
PS:当我使用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