Skip to content
Advertisement

Is it possible to share a numpy array that’s not empty between processes?

I thought that SharedMemory would keep values of target arrays, but when I actually tried it, it seems it doesn’t.

JavaScript

In the code above, the 2 processes can share one array(a) and access to it. But the value that was given before sharing(a[‘value’] = 100) is missing. Is it just natural or is there any way to keep the value even after sharing?

Advertisement

Answer

Here’s an example of how to use shared_memory using numpy. It was pasted together from several of my other answers, but there are a couple pitfalls to keep in mind with shared_memory:

  • When you create a numpy ndarray from a shm object, it doesn’t prevent the shm from being garbage collected. The unfortunate side effect of this is that the next time you try to access the array, you get a segfault. From another question I created a quick ndarray subclass to just attach the shm as an attribute, so a reference sticks around, and it doesn’t get GC’d.
  • Another pitfall is that on Windows, the OS does the tracking of when to delete the memory rather than giving you the access to do so. That means that even if you don’t call unlink, the memory will get deleted if there are no active references to that particular segment of memory (given by the name). The way to solve this is to make sure you keep an shm open on the main process that outlives all child processes. Calling close and unlink at the end keeps that reference to the end, and makes sure on other platforms you don’t leak memory.
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement