c ++试图添加Peterson算法以避免共享内存中的竞争条件

c++ trying to add Peterson algorithm to avoid race condition in shared memory

我写了两个程序(程序 1 和程序 2)使用共享内存相互通信。程序 1 从文件中读取一个句子,并在修改后将其传递给下一个程序(程序 2),以获取每个单词的首字母及其大小。我遇到了竞争条件问题。我添加了 Peterson 算法,但是一旦我执行了 2 个程序,一个在前台,一个在后台,我没有得到任何结果。

-一旦我删除了 Peterson 算法,我的程序就可以运行了

-我在 linux 使用 c++

节目 1

#include<iostream>
#include<fstream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

int filesize(){

ifstream input;
input.open("file1.txt");

string temp;

int i = 0;

while(input>>temp){i++;}

input.close();  

return i;
}

struct shdata
{   
char c;      
    int n;
    int size;
    bool flag[2];
    int turn;
};

int main(){
 ifstream input;
     input.open("file1.txt");   

int shmid;
key_t key = 8006;

struct shdata *shm;



shmid = shmget(key, sizeof(struct shdata), IPC_CREAT | 0666);

 if(shmid < 0){
     cout<<"Error .. Can not get memory\n";
     exit(0);
 }

     shm = (struct shdata *)shmat (shmid, NULL, 0);

     if(shm <= (struct shdata *)(0))
     {
      cout<<"Errors.. Can not attach\n";
      exit(1);
     }
     shm->flag[0]=false;
     shm->flag[1]=true; 
     string temp;


     while(input>>temp){
     shm->flag[0]=true;
     shm->turn = 1;          
     while(shm->flag[1]== true && shm-> turn == 1 );

     shm->c=temp[0];
     shm->n=temp.size();
     shm->size = filesize();


     shm->flag[0]=false;  
     sleep(1);
     }


return 0;
}

节目 2

    #include<iostream>
    #include<fstream>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <unistd.h>

    using namespace std;

    int filesize(){

ifstream input;
input.open("file1.txt");

string temp;

int i = 0;

while(input>>temp){i++;}

input.close();  

return i;
    }

    struct shdata
    {   
char c;      
    int n;
    int size;
    bool flag[2];
    int turn;
    };

    int main(){

int shmid;
key_t key = 8006;

struct shdata *shm;



    shmid = shmget(key, sizeof(struct shdata), 0);
if(shmid < 0)
   {
  cout<<"Error .. Can not get memory\n";
  exit(0);
   }

   shm = (struct shdata *)shmat (shmid,0, 0);

   if(shm <= (struct shdata *)(0))
   {
   cout<<"Error .. Can not attach\n";
   exit(1);
   }
   int c =0;
   while(c<shm->size){

shm->flag[1] = true;
    shm->turn=0; 

 while( shm->flag[0]==false && shm->turn == 0);

sleep(1);     
 for(int i = 0; i < shm->n ;i++)
 {
    cout<<shm->c;
 }
 cout<<endl;

 shm->flag[1]=false;

 c++;
 }
shmctl(shmid, IPC_RMID, NULL);

return 0;
}        

程序 2 永远不会进入 while(c<shm->size) 循环,因为此时 shm->size 为 0。为了绕过它,程序 1 应该在程序 2 到达该点之前初始化 shm->size。这可能会导致另一个竞争条件,因为似乎没有任何机制可以确保共享内存在程序 2 开始使用之前由程序 1 初始化。

它似乎在没有 Peterson 算法的情况下工作,因为在那种情况下程序 1 不会等待标志并在循环中进一步初始化 shm->size

您正在使用 flag 成员来同步您的 2 个程序,但这无法工作,因为您无法假设 read/writes 的顺序。您必须使用小方言才能使您的两个程序以正确的顺序启动。