我有以下两个与共享内存通信的进程。我应该如何修改这些,以便我可以在同一台机器上运行两个副本,而不会相互干扰?即p1仅与p2共享内存,而p1.1仅与p2.1共享内存
谢谢!
流程1:
int main(int argc, char* argv[]){
srand(time(NULL));
//use old shared memory if exists else create a new one
shared_memory_object shm(open_or_create, "shared_memory", read_write);
//set the size of the memory object
shm.truncate(sizeof(shared_memory_buffer));
//map the whole shared memory in this process
mapped_region region(shm,read_write);
//get the region address
void * addr = region.get_address();
//create a shared memory buffer in memory
shared_memory_buffer *data = new (addr) shared_memory_buffer;
while(true){
//wait until the written number gets executed
data->writer.wait();
//print the square root of the original value
std::cout << "Square Root: " << data->value << "\n";
//create the original value
data->value = atoi(argv[1]); //rand() % 100 + 1;
sleep(1);
//reader can execute written number
data->writer.post();
sleep(rand()%5 +1);
}
return 0;
}
过程2:
int main(int argc, char* argv[]){
//create a shared memory object.
shared_memory_object shm(open_only, "shared_memory",read_write);
//Map the whole shared memory in this process
mapped_region region(shm,read_write);
//get the region address
void * addr = region.get_address();
//Obtain the shared structure
shared_memory_buffer * data = static_cast<shared_memory_buffer *>(addr);
while(true){
//wait until a number gets available
data->writer.wait();
//print the original value
std::cout << "Original Value: " << data->value << "\n";
//create the sqrt of the original value
data->value = atoi(argv[1]); //sqrt(data->value);
//sleep(1);
//writer can print sqrt
data->writer.post();
sleep(rand()%5 +1);
}
return 0;
}
两个进程都使用此结构:
struct shared_memory_buffer {
//writer initialized with one to start
//reader have to wait
shared_memory_buffer(): writer(1), reader(1), value(0){}
interprocess_semaphore writer, reader;
float value;
};
答案 0 :(得分:0)
为共享内存领域使用不同的名称(即,而不是“shared_memory”)
包含GUID是常见做法。