简体   繁体   中英

Writing to boost shared memory

It must have been straight forward answer, but I haven't found anywhere how to do it...

I have successfully created a shared memory segment using boost IPC system as in the example:

boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only, "MySharedMemory", 65536);

sharedData = segment.construct<MyType>("Test")(0, 0.2);

I have also been able to read the values from a different process. What I cannot understand is how to edit the values of this variable (If I'm allowed to call "Test" as a variable) and read them from the other process. I want to be on a loop and write these values.

Thank you

This isn't a good idea because there is no way of enforcing concurrency on a shared memory block. In the same way a shared resource needs to be protected from multiple threads crashing into each other (eg with a mutex or critical section) the same is true for a shared memory block.

Without an extra signalling mechanism using something like named pipes, there is no way of safely signalling that a shared memory block is

  • available to read
  • available to write
  • updated

If you create your memory block with the read_write flag it will set the correct Windows permissions. The example in the boost documentation shows this.

using boost::interprocess;
shared_memory_object shm_obj
   (open_only                    //only open
   ,"shared_memory"              //name
   ,read_write                   //read-write mode
   );

As @Konrad suggested, using shared memory so loosely is not A Good Thing™. That being said, Boost does provide interprocess synchronization utilities that work much the same as those traditionally used between threads.

Give this page of the documentation a good read (particularly the section on Conditions) and see if that might give you an idea of what should be aiming for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM