使用信号量进行进程同步

发布于 2024-12-07 16:05:30 字数 603 浏览 1 评论 0原文

问题就在这里。 我希望两个进程交替发生,完整的问题就在这里。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硬不硬你别怂 2024-12-14 16:05:30

另一种解决方案是:

Semaphore as = 1;
Semaphore bs = 0;

A() {
  int counter = 0;
  while(TRUE) {
    if(counter % 2 == 0)
      P(as);
    print("A"); // and whatever A does
    counter++;
    if(counter % 2 == 0)
      V(bs);
  }
}

B() {
  P(bs);
  print("B"); // and whatever B does
  V(as); 
}

这个想法是 A 每第二轮等待 B(第 0 轮除外)。

An alternative solution would be:

Semaphore as = 1;
Semaphore bs = 0;

A() {
  int counter = 0;
  while(TRUE) {
    if(counter % 2 == 0)
      P(as);
    print("A"); // and whatever A does
    counter++;
    if(counter % 2 == 0)
      V(bs);
  }
}

B() {
  P(bs);
  print("B"); // and whatever B does
  V(as); 
}

The idea is that A waits for B on every 2nd turn (execept the 0th).

や三分注定 2024-12-14 16:05:30

我认为总体思路是正确的,但术语比较奇怪。等待信号对通常用于条件变量(尽管例如 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 with semaphore_down and signal with semaphore_up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文