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

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

本文关键字:内存 共享 条件 竞争 添加 Peterson 算法 c++      更新时间:2023-10-16

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

-一旦我删除Peterson算法我的程序工作

-i'm working in Linux using 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 memoryn";
     exit(0);
 }
     shm = (struct shdata *)shmat (shmid, NULL, 0);
     if(shm <= (struct shdata *)(0))
     {
      cout<<"Errors.. Can not attachn";
      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 memoryn";
  exit(0);
   }
   shm = (struct shdata *)shmat (shmid,0, 0);
   if(shm <= (struct shdata *)(0))
   {
   cout<<"Error .. Can not attachn";
   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。这可能会导致另一个竞争条件,因为似乎没有任何机制来确保程序1在程序2开始使用共享内存之前对其进行初始化。

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

你正在使用flag成员来同步你的2个程序,但这不能工作,因为你不能假设读/写的顺序。您必须使用一种小的方言,以使您的两个程序以正确的顺序开始。