2

I am using boost::interprocess::managed_shared_memory to create memory to be shared across processes.

Following are the steps taken:

  1. step

    a) Create memory.
    
  2. step

    a) Open memory. 
    b) Write to memory
    
  3. step

    a) Open memory.
    b) Read from memory.
    c) Open memory.
    d) Read from memory.
    e) Open memory.
    f) Read from memory.
    g) ...... and so on and so forth!
    

Now, the question is, in step number 3, I am opening the memory again-and-again before reading it! I think this is redundant behavior.

How can I read multiple number of times by opening it only once?

Actually the open command is quite expensive in terms of performance, and this is proving to be a bottleneck in my application.

CinCout
  • 9,486
  • 12
  • 49
  • 67

2 Answers2

5

The idea should be to only open the shared resource (memory in this case) only once, and reuse the same handle/variable/object to assess it time-and-again.

Any of the following approaches will do:

  1. If all the accesses are in a single function, use a variable with local scope to maintain the lifetime of the shared memory. Moreover, if the said method has other statements that do not need to access the shared resource, the resource can itself be enclosed in a pair of { } to ensure a local scope within the function scope.

Alternatively, same can be saved as pointer, and passed around functions in case the workflow involves calling several methods that use the shared resource.

  1. Wrap the shared resource as an object (or a pointer) as the member variable of a class. The said class can either be created just to manage the shared memory, or an existing class which is utilizing the resource can take up ownership, depending upon the design.
CinCout
  • 9,486
  • 12
  • 49
  • 67
2

Many of the samples have the managed_shared_memory in the main function for brevity.

You should, however, make it a member of a relevant class (with the responsibility to manage the lifetime of your shared memory mapping).

You could of course, keep it as a local variable in main, but then you'd be forced to keep passing it around in any function calls. (I do NOT recommend making it a global variable. Or a singleton for that matter).

sehe
  • 374,641
  • 47
  • 450
  • 633