c++尝试添加Peterson算法以避免共享内存中的竞争条件
c++ trying to add Peterson algorithm to avoid race condition in shared memory
我编写了两个程序(程序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个程序,但这不能工作,因为你不能假设读/写的顺序。您必须使用一种小的方言,以使您的两个程序以正确的顺序开始。
相关文章:
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 使用Boost Interprocess创建托管共享内存需要很长时间
- 多个"常量引用"变量可以共享同一个内存吗?
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 字符串共享内存映射的向量
- CUDA 使用共享内存平铺 3D 卷积实现
- 共享内存:MapViewOfFile 返回错误 5
- 在共享缓冲区内存中创建 ::std::string 对象
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- Directx 12 :在两个进程之间共享图形内存
- 有没有办法列出所有共享内存对象的名称?
- 子进程更新共享 mmap 内存,但父进程没有更改
- C++线程之间的内存共享
- 使用Windows共享内存共享小数据
- 更有效地使用fork()和写时复制内存共享
- 从托管代码到非托管代码跨共享内存共享整数数组
- 通过内存共享c++对象
- 内存共享;继承;基实例和派生实例;c++
- Matlab与c++在MEX中的内存共享
- 跨共享内存共享 std::字符串