jeudi 8 avril 2021

Can I cause a Meyers singleton to reinitialize in forked child processes?

Say I have a meyers singleton

Data& get() {
  static Data data = initialization_work();
  return data;
}

that's already been used and initialized in a parent process. I then fork(2) a child process, and in the child process data may need to be different (ie, i'd like initialization_work() to rerun the first time get() is called in the child).

First, will data automatically be reinitialized in the forked child? My suspicion is no, based on my mediocre knowledge of linux (forked child VA space is a duplicate of parent mapped to physical memory copy-on-write, so i assume child process will see data as already initialized and won't redo initialization_work()) and a couple other questions (C static variables and linux fork, C++ static variable and multiple processes).

Second, if data will not be reinitialized in the child by default, is there a way to force reinitialization the first time the child calls get()? If not, I can try to figure out some other pattern (and I'd really appreciate any suggestions on what pattern might fit this use case).

Aucun commentaire:

Enregistrer un commentaire