gpierris
gpierris

Reputation: 856

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

Upvotes: 1

Views: 4794

Answers (2)

jpm
jpm

Reputation: 3155

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.

Upvotes: 1

Konrad
Konrad

Reputation: 40947

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 (e.g. 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
   );

Upvotes: 2

Related Questions