0

I am trying to see how a lambda function along with std::function can be used in a program where different child processes are created and sharing contents of lambda. I have code something like which is to be used among different with child process created from parent process fork.

struct Foo {
   std::function<void()> bar;
};
void some_func(void *a, void *b)
{
}
int main()
{
 void *a, *b;
 auto func= [=]() {       
        some_func(a, b);
    };
  Foo f{func};
}

I see some problems accessing this allocation across different processes. From what I have read on this forum about lambda expression and std::function can allocate space on heap. Probably when value capture list in the list grows it would not be just a stack object and hence it could not not be properly shared among the processes. I came across boost::interprocess library which allows to use allocators in multi process environment for sharing for containers like vector etc. Unfortunately as I understand allocators for std::function have been deprecated since C++17. So what are the alternatives to use have lambda expression as above in multi process environment when data is supposed to be shared?

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
Parimal
  • 11
  • 3
  • Do you mean you want the lambda to access the same `a` and `b` in all child-processes? If you make them point to valid memory-areas before you fork new processes, and only *read* from the memory in the child-processes, then there's nothing special you need to do. If you want to *write* to the memory, and have it be visible to all sibling processes, then you need to use *shared memory* to share the memory between processes. – Some programmer dude Jul 13 '22 at 06:34
  • As for sharing the lambda itself, code is already "shared" since there will only be one copy of all code in memory. And "sharing" the captured data only makes sense if you consider the points from my first comment. – Some programmer dude Jul 13 '22 at 06:36
  • 1
    "can allocate space on heap" is a red herring, neither stack nor heap are shared between parent/child processes. The child only gets a copy of the parent, which is often implemented as copy-on-write, but no sharing of mutable data takes place. – Ulrich Eckhardt Jul 13 '22 at 06:37
  • 3
    And all in all, this seems very much like an [XY problem](https://xyproblem.info/), where you want help with your wanted solution, but you don't tell us the actual underlying problem you're trying to solve. – Some programmer dude Jul 13 '22 at 06:38
  • I think I did not correctly describe the question and the example code. But I was looking for something [like](https://stackoverflow.com/questions/38127290/placement-new-for-lambda-capture) when the memory is supposed to be shared – Parimal Jul 15 '22 at 21:52

0 Answers0