SharedMemory is a new feature of python3.8. It mainly uses memory sharing and is very convenient to use

Use the documentation link: docs.python.org/zh-cn/3/lib…

We can try creating a new object:

from multiprocessing import shared_memory
shm_a = shared_memory.SharedMemory(create=True, size=10)
Copy the code

This method creates a new space to store a block of memory, and we can also look at its contents:

>>> shm_a
SharedMemory('psm_d5082db5', size=10)
Copy the code

We can see that we are actually creating a shared memory card of size 10 named PSM_D5082DB5

Of course, we can print the name directly:

>>> shm_a.name
'psm_b370a3a5'
Copy the code

We can also look at what’s in this block of memory, just use buf, and actually initialize everything to zero, okay

>>> shm_a.buf
<memory at 0x7f3af310b640>
>>> list(shm_a.buf)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Copy the code

We can also create a new block of the same memory:

shm_b = shared_memory.SharedMemory(shm_a.name)
Copy the code

Now let’s think about the question, are these two blocks of memory the same block of memory?

We can look at the answer:

>>> shm_a is shm_b
False
>>> shm_a==shm_b
False
Copy the code

The answer is the same block of memory, but now we can see if the contents are the same:

>>> shm_b.buf is shm_b.buf
True
>>> shm_b.buf==shm_b.buf
True
Copy the code

Now the content is the same. How does that work?

We can look at an experiment:

>>> id(shm_a)
139891162754352
>>> id(shm_b)
139891162754496
Copy the code

It turns out that SHm_A and SHm_B are inherently different things, with different addresses

So why are the contents the same? We can draw a picture:

We can see that shm_A and SHm_b share the same data, not the same thing, because they are not the same address at all, but shm_A and SHm_b use the same memory block

Shm_a is of type shm_a. It looks like a list, but is not:

>>> type( shm_a.buf)
<class 'memoryview'>
Copy the code

Similar to list, we also use slicing to get data:

>>> shm_a.buf[-1] 0 >>> shm_a.buf[-1]=2 >>> list(shm_a.buf) [0, 0, 0, 0, 0, 0, 0, 0, 0, 2] >>> list(shm_b.buf) [0, 0, 0, 0, 0, 0, 0, 0, 2]Copy the code

So far, we haven’t used the concept of sharing, because we eventually need to use this data in another process, so if you create this data on one terminal, but you can get it directly on the other terminal

Here’s an example:

We created the memory block before another terminal used it:

>>> existing_shm = shared_memory.SharedMemory('psm_b370a3a5')
>>> list(existing_shm.buf)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Copy the code

As you can see, we can just get it