How to sync processes using semaphore

对着背影说爱祢 提交于 2019-12-12 03:45:13

问题


let's say I have 3 processes including a parent process I have to execute I program in sequence of P3,P1,P2. Guys please help me how I can start the computation from process P3.

I need the out as {0,1,2,3,4,5,.. max}

For the reference my code snapshot is :-

 #define SEM_NAME "//test.mutex"
//#define SEM_NAME2 "//test2.mutex"

int main(int argc, char const *argv[]) {
  int max = 0, i =0;
  sem_t *sem;
  sem_t *sem2;
  pid_t  pid, pid2;
  sem = sem_open(SEM_NAME, O_CREAT, O_RDWR, 1);
  sem_unlink(SEM_NAME);
  if (sem==SEM_FAILED) {
    printf("%s sem_open failed!", SEM_NAME);
    return (-1);
  }
  // sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 0);
  // sem_unlink(SEM_NAME2);
  // if (sem2==SEM_FAILED) {
  //   printf("%s sem_open failed!", SEM_NAME2);
  //   return (-1);
  // }
  printf("Enter the maximum number\n");
  scanf("%d", &max);
  pid = fork();
  if(pid == 0)
  {
    i = 2;
    pid2 = fork();
    if(pid2 == 0)
    {
      i = 0;
    }
    else
    {
      sleep(2);
    }
  }
  else
  {
    i = 1;
    sleep(1);
  }
  //do
  {
    sem_wait(sem);
    for (; i <= max;) {
      printf("pid %d done and value is %d\n", getpid(),i);
      i = i + 3;
    }
    sem_post(sem);
  } //while(i <= max);
  wait(NULL);
  return 0;
}

when I run the program I get following output {0,3,,6,1,4,7,2,5,8}

I need a way I which first process should print a number and it should let other process to print his number and at the last third should print.

I need a way that each and get there turn sequentially.

Hope I am clear with the question


回答1:


Here's pseudo code of how you can achieve order P3, P1, P2

//semaphores for P1, P2, P3 respectively
semaphore s1=0;
semaphore s2=0;
semaphore s3=1;     //coz P3 needs to go first 


//for p3
wait(s3)
  //do p3 here
signal(s1)          //signal for P1 to start


//for p1
wait(s1)
  //do p1
signal(s2)           // signal to start P2


//for p2
wait(s2)
   //do p2
signal(s3)            //signal to start p3 again if that is required or you can omit this if not required


来源:https://stackoverflow.com/questions/43236175/how-to-sync-processes-using-semaphore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!