2

所以,我正在为家庭作业编写代码,必须使用 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;
}

我做了这个,不知道为什么它不起作用。两个进程都启动了函数“进程”,但没有更进一步。知道我在哪里做错了吗?

4

1 回答 1

2

哦,天哪,我只花了 1-2 小时调试这个,发现我用if(i=0)的是if(i==0)..

于 2013-04-19T12:14:35.853 回答