[英]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;
}
int a=0;
) 我应该如何得出这些答案?
我只是假设您是指通过“打印选项”打印的a
和b
不同值组合。
所以一开始你有a
和b
= 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
不能被其他线程覆盖。 因此输出将始终是。
a=1, b=1
a=1, b=2
编辑:忘记第一个问题的第三个打印方案
a=2, b=1
a=2, b=2
如果分别读写a
(首先读取t1然后读取t2),但是在第一个线程执行打印之前,会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.