开发者

Process Synchronisation using semaphores

开发者 https://www.devze.com 2023-04-09 03:48 出处:网络
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

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 exec开发者_开发百科uted 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?


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消