使用信号量进行进程同步
问题就在这里。 我希望两个进程交替发生,完整的问题就在这里。
Q. 系统中有两个进程A和B。系统启动时,进程A执行了两次,进程B执行了一次。只有进程A执行了两次,进程B才能执行。一旦进程A执行完毕,它就不能再次执行,直到进程B执行完毕。上述限制允许进程A和B以如下方式执行。
AABAABAAB...
使用计数信号量为进程 A 和 B 编写伪代码以实现所需的同步。
这是我的尝试。
解决方案:
过程A
var a=1,b=0,i;
begin
repeat
wait(a);
for(i=0;i<2;i++)
printf("A"); // conidering this is what process a does.
signal(b);
forever
end
过程B
begin
repeat
wait(b);
printf("B"); //considering this is what process B does.
signal(a);
forever
end
这是正确的吗?
Here is the problem.
I want two processes to occur alternatively, the complete problem is here.
Q. In a system ther are two processes named A and B.When the system starts,the process A executes twice then process B executes once.The Process B cannot execute until process A has executed twice. Once Process A haas executed it can not execute again until process B has executed. The restriction mentioned above allows the process A and B to execute in the following manner.
AABAABAAB...
Write the pseudocode for Process A and B using counting semaphore to achieve the desired synchronisation.
Here is my attemp for this.
Solution:
Process A
var a=1,b=0,i;
begin
repeat
wait(a);
for(i=0;i<2;i++)
printf("A"); // conidering this is what process a does.
signal(b);
forever
end
Process B
begin
repeat
wait(b);
printf("B"); //considering this is what process B does.
signal(a);
forever
end
Is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种解决方案是:
这个想法是 A 每第二轮等待 B(第 0 轮除外)。
An alternative solution would be:
The idea is that A waits for B on every 2nd turn (execept the 0th).
我认为总体思路是正确的,但术语比较奇怪。等待信号对通常用于条件变量(尽管例如 POSIX 信号量使用 post/wait)。
我建议您将
wait
替换为semaphore_down
,将signal
替换为semaphore_up
。I think that the general idea is correct, but the terminology is rather strange. Wait-signal pair is usually used for condition variables (although e.g. POSIX semaphorese use post/wait).
I suggest you substitue the
wait
withsemaphore_down
andsignal
withsemaphore_up
.