有人可以解释这两个问题的解决方案(c program,mutex,threads)吗?

Can someone explain the solution of these two questions (c program,mutex,threads)?

我有一个旧考试的问题及其答案,但我不明白解决方案。有人可以给我解释一下吗?

给出这个 C 程序:

int a = 0;
int b = 0;
pthread_mutex_t m;

void * f()
{
    _________________ (Empty Line for question number 2)
    a = a + 1;
    pthread_mutex_lock(&m);
    b = b + 1;
    printf("a = %d, b = %d\n", a, b);
    pthread_mutex_unlock(&m);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    pthread_mutex_init(&m, NULL);
    pthread_create(&t1, NULL, &f, NULL);
    pthread_create(&t2, NULL, &f, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}
  1. 程序可以发出多少种不同的打印输出? (答案是 3)
  2. 您可以在空行中添加什么代码来将各种打印选项减少到 1? (答案是int a=0;

我应该如何得出这些答案?

我假设您指的是 ab 的不同值组合,这些组合由 "print options".

打印

所以一开始你有 ab = 0

然后您创建线程并且在 a 上存在竞争条件,因此结果不确定。可能发生的情况:

t1:read a=0  write a=0+1
t1:read b=0  write b=0+1
t1:print `a=1, b=1`
t2:read a=1 write a=1+1
t2:read b=1 write b=1+1
t2:print `a=2, b=2`

可能发生的另一件事:

t1: read a =0
t2: read a =0
t1: write a =0+1
t2: write a =0+1
t1: read b=0  write b=0+1
t1: print `a=1, b=1`
t2: read b=1 write b=1+1
t2: print `a=1, b=2`

这是一种可能。 a 的读写随时都可能发生。但这些是不同输出如何发生的例子。 t1 和 t2 也可以互换。不能保证 t1 先执行。

第二个答案用 a 局部 a 隐藏了全局 a ,它不能被其他线程覆盖。所以输出总是。

a=1, b=1 a=1, b=2

编辑:忘记了第一个问题的第三个打印场景

a=2, b=1 a=2, b=2

如果 a 是分开读写的(首先读写 t1,然后读写 t2)但在第一个线程执行打印之前,就会发生这种情况。