简体   繁体   中英

Is there a way to share a variable (within a shared lib) between processes?

I would like to initialize a complex variable within a shared library, but only once. Afterwards I would like to share the now initialized variable with all processes that are using this lib.

Example

  • Let's say the lib is called libgetx.so and it is having the functions

    • int get_variable_x() - which returns the value of a variable called x .
    • init_x(5) - which is initializing x
  • I would like to init x only once (maybe at loading of the lib) - imagine something costly, like parsing a config-file.

  • Now, everytime I call get_variable_x() from a process that is linked to the shared lib, I would like to be able to read out x . But without initializing it again (since it already in another process).

Is this possible? I am not sure what exactly is happening in the system when you are calling a function from a shared lib from different processes, but it looks like they do not share the same space.

Actual Situation : I am on Linux. I would like to parse a yaml config file and get the config values via a shared library instead of parsing the config file again and again. I am using yaml-pp and yaml-cpp-path for getting the values. It would then call eg get_config("something.id ) to get the id` which is defined in the yaml file.

The specific answer of how to go about doing this would be platform-specific, but you want to look into whatever shared memory facilities your platform provides. In short, you'd set up a mutex or something equivalent and wait for the mutex to unlock.

Once the mutex unlocks, the exact order of steps depends on how shared memory on your platform works, but you'd need to create/attach to the memory segment, find out if some other process has created the segment already, and if not then write the shared data to it.

After all this is done, release the mutex and go about your merry way.

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