Process 使用信号量的进程同步

Process 使用信号量的进程同步,process,operating-system,semaphore,Process,Operating System,Semaphore,问题就在这里。 我希望两个过程交替发生,完整的问题就在这里 在一个系统中,有两个名为a和B的进程。当系统启动时,进程a执行两次,然后进程B执行一次。进程B在进程a执行两次之后才能执行。一旦执行了进程A,它就不能再次执行,直到执行了进程B。上述限制允许过程A和B以以下方式执行 阿巴巴布 使用计数信号量为进程A和进程B编写伪代码,以实现所需的同步 这是我的计划 解决方案: 过程A var a=1,b=0,i; begin repeat wait(a); for(i=0;i<2;

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

在一个系统中,有两个名为a和B的进程。当系统启动时,进程a执行两次,然后进程B执行一次。进程B在进程a执行两次之后才能执行。一旦执行了进程A,它就不能再次执行,直到执行了进程B。上述限制允许过程A和B以以下方式执行

阿巴巴布

使用计数信号量为进程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

这是正确的吗?

我认为总体思路是正确的,但术语相当奇怪。等待信号对通常用于条件变量(尽管POSIX信号使用post/Wait)


我建议您将
等待
替换为
信号量下降
信号
替换为
信号量上升
,另一种解决方案是:

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圈除外)

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); 
}