如何清除/覆盖共享内存中的所有数据?

问题描述 投票:0回答:1

我需要覆盖共享内存中的所有先前写入的数据(multiprocessing.shared_memory)。这是示例代码:

from multiprocessing import shared_memory
import json


shared = shared_memory.SharedMemory(create=True, size=24, name='TEST')

data_one = {'ONE': 1, 'TWO': 2}
data_two = {'ACTIVE': 1}

_byte_data_one = bytes(json.dumps(data_one), encoding='ascii')
_byte_data_two = bytes(json.dumps(data_two), encoding='ascii')

# First write to shared memory
shared.buf[0:len(_byte_data_one)] = _byte_data_one
print(f'Data: {shared.buf.tobytes()}')

# Second write
shared.buf[0:len(_byte_data_two)] = _byte_data_two
print(f'Data: {shared.buf.tobytes()}')

shared.close()
shared.unlink()

输出:

首先写入:b'{"ONE": 1, "TWO": 2}\x00\x00\x00\x00'第二次写入:b'{"ACTIVE": 1}WO": 2}\x00\x00\x00\x00'

输出是可以理解的,因为第二次写操作从索引0开始并以_byte_data_two长度结束。 (shared.buf[0:len(_byte_data_two)] = _byte_data_two

我需要对共享内存进行的每一次新写入都必须覆盖以前的所有数据。

我在每次新写入共享内存之前都尝试过shared.buf[0:] = b'',但最终得到ValueError: memoryview assignment: lvalue and rvalue have different structures另外,我在每次新写入后都尝试过此shared.buf[0:len(_bytes_data_two)] = b'',其结果相同。

关注此结果:首次写入:b'{"ONE": 1, "TWO": 2}\x00\x00\x00\x00'第二次写入:b'{"ACTIVE": 1}\x00\x00\x00\x00' 第一次写入没有多余的“ WO”:2}

如何覆盖共享存储器中所有以前写入的数据?

multiprocessing shared-memory python-3.8
1个回答
0
投票

最简单的方法可能是先创建一个零填充字节数组,类似于:

def set_zero_filled(sm, data):
  buf = bytearray(sm.nbytes)
  buf[:len(data)] = data
  sm.buf[:] = buf

您可以用作:

set_zero_filled(shared, json.dumps(data_two).encode())
© www.soinside.com 2019 - 2024. All rights reserved.