不知道Dekkers算法我做错了什么

时间:2013-04-19 11:55:39

标签: c++ algorithm multiprocessing

所以,我正在编写一个家庭作业的代码,必须做Dekkers算法的互斥。

#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int Id; /* Segment Id */
int *TURN;
int *FLAG_I;
int *FLAG_J;

void get_out_of_critical(int i)
{
   if(i=0){
      *TURN=1;
      *FLAG_I=0;
   }
   else{
      *TURN=0;
      *FLAG_J=0;
   }

}

void get_in_critical(int i)
{
   if(i=0){
      *FLAG_I=1;
      while(*FLAG_J!=0){
         if(*TURN==1){
            *FLAG_I = 0;
            while(*TURN==1){}
         *FLAG_I=1;
         }
      }
   }
   if(i=1){
   *FLAG_J=1;
   while (*FLAG_I!=0){
         if(*TURN==0){
            *FLAG_J = 0;
            while(*TURN==0){}
         *FLAG_J=1;
         }
      }
   }

}

void process(int i)
{
   for(int k=1;k<=5;k++){
       cout<<"Process - "<<i<<endl;
       get_in_critical(i);
       for(int m=1;m<=5;m++){
           cout<<"Process: "<<i+1<<", K.O. num: "<<k<<" ("<<m<<"/5)"<<endl;
      }
      get_out_of_critical(i);
   }
}

void del(int sig)
{
   /* free shared memory */
   (void) shmdt((char *) TURN);
   (void) shmdt((char *) FLAG_I);
   (void) shmdt((char *) FLAG_J);
   (void) shmctl(Id, IPC_RMID, NULL);
   exit(0);
}

int main()
{
   /* allocating shared memory */
   Id = shmget(IPC_PRIVATE, sizeof(int)*100, 0600);

   if (Id == -1)
      exit(1);

   TURN = (int *) shmat(Id, NULL, 0);
   *TURN = 0;
   FLAG_I = (int*) shmat(Id, NULL, 0);
   FLAG_J = (int*) shmat(Id, NULL, 0);
   *FLAG_I = 0;
   *FLAG_J = 0;
   sigset(SIGINT, del);// in case of signal interrupt, delete shared memory

   /* starting paralel processes */
   if (fork() == 0) {
      process(0);
      exit(0);
   }
   if (fork() == 0) {
      process(1);
      exit(0);
   }
   wait();
   wait();
   del(0);

   return 0;
}

我已经做到了,不知道为什么它不起作用。这两个进程都启动了“进程”功能,但是没有进一步说明..任何想法我在哪里做错了什么?

1 个答案:

答案 0 :(得分:2)

天啊,我只是花了1-2小时调试这个,发现我使用了if(i=0)而不是if(i==0) ..

相关问题