互斥问题
请看一下下面的伪代码:
boolean blocked[2];
int turn;
void P(int id) {
while(true) {
blocked[id] = true;
while(turn != id) {
while(blocked[1-id])
/* do nothing */;
turn = id;
}
/* critical section */
blocked[id] = false;
/* remainder */
}
}
void main() {
blocked[0] = false;
blocked[1] = false;
turn = 0;
parbegin(P(0), P(1)); //RUN P0 and P1 parallel
}
我认为可以使用上面的代码实现一个简单的互斥解决方案。但这不起作用。有谁知道为什么吗?
任何帮助将不胜感激!
Please take a look on the following pseudo-code:
boolean blocked[2];
int turn;
void P(int id) {
while(true) {
blocked[id] = true;
while(turn != id) {
while(blocked[1-id])
/* do nothing */;
turn = id;
}
/* critical section */
blocked[id] = false;
/* remainder */
}
}
void main() {
blocked[0] = false;
blocked[1] = false;
turn = 0;
parbegin(P(0), P(1)); //RUN P0 and P1 parallel
}
I thought that a could implement a simple Mutual - Exclution solution using the code above. But it's not working. Has anyone got an idea why?
Any help would really be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在这个例子中,由于以下原因,不能保证互斥:
我们从以下情况开始:
P1 现在正在执行,并跳过
现在的情况:
现在 P0 正在执行。它通过了第二个 while 循环,准备执行关键部分。而当P1执行时,将turn设置为1,也准备好执行临界区。
顺便说一句,这种方法最初是由海曼发明的。 1966 年,他将其发送给 ACM Communications
Mutual Exclusion is in this exemple not guaranteed because of the following:
We begin with the following situation:
P1 is now executes, and skips
The situation is now:
Now P0 executes. It passes the second while loop, ready to execute the critical section. And when P1 executes, it sets turn to 1, and is also ready to execute the critical section.
Btw, this method was originally invented by Hyman. He sent it to Communications of the Acm in 1966
在本例中,由于以下原因,无法保证互斥:
我们从以下情况开始:
执行运行如下:
Mutual Exclusion is in this exemple not guaranteed because of the following:
We begin with the following situation:
The execution runs as follows:
这是作业,还是一些嵌入式平台?是否有任何原因不能使用 pthreads 或 Win32(相关)同步原语?
Is this homework, or some embedded platform? Is there any reason why you can't use pthreads or Win32 (as relevant) synchronisation primitives?
也许您需要声明为阻塞并转为易失性,但如果不指定编程语言,则无法知道。
Maybe you need to declare blocked and turn as volatile, but without specifying the programming language there is no way to know.
并发不能这样实现,特别是在多处理器(或多核)环境中:不同的核/处理器有不同的缓存。这些缓存可能不一致。下面的伪代码可以按所示顺序执行,并显示结果:
您需要硬件知识来实现并发。
Concurrency can not be implemented like this, especially in a multi-processor (or multi-core) environment: different cores/processors have different caches. Those caches may not be coherent. The pseudo-code below could execute in the order shown, with the results shown:
You need hardware knowledge to implement concurrency.
编译器可能已经优化了“空”while 循环。将变量声明为 volatile 可能会有所帮助,但不能保证在多处理器系统上足够。
Compiler might have optimized out the "empty" while loop. Declaring variables as volatile might help, but is not guaranteed to be sufficient on multiprocessor systems.