store variables from foreach

I'm seeing that the function takes inputs and uses them to modify global objects defined elsewhere, I'm doubtful whether this approach/architecture is suitable for parallelizing. I think the function would be better to be more explicit about the object(s) to be modified, passing them in as parameters maybe ? and preparing a single return object containing anything to be passed back. In that way foreach would combine the results.
I don't want to dissuade you from working on this, but I don't think what you are doing is trivial, and will take a lot of thought and experimentation to get right...
It might be that a reprex (of your non-parallelised approach) is the best way to go if you wish to engage this communities competative spirit to engineer up a parallel solution :smiley:
FAQ: How to do a minimal reproducible example ( reprex ) for beginners