我最难在进程之间共享字符串。我查看了以下Q1,Q2,Q3,但在实际示例中仍然失败。如果我正确理解了文档,那么查找应该自动完成,因此设置/读取时不应该出现竞争条件。这是我得到的:
#!/usr/bin/env python3
import multiprocessing
import ctypes
import time
SLEEP = 0.1
CYCLES = 20
def child_process_fun(share):
for i in range(CYCLES):
time.sleep(SLEEP)
share.value = str(time.time())
if __name__ == '__main__':
share = multiprocessing.Value(ctypes.c_wchar_p, '')
process = multiprocessing.Process(target=child_process_fun, args=(share,))
process.start()
for i in range(CYCLES):
time.sleep(SLEEP)
print(share.value)
产生:
Traceback (most recent call last):
File "test2.py", line 23, in <module>
print(share.value)
File "<string>", line 5, in getvalue
ValueError: character U+e479b7b0 is not in range [U+0000; U+10ffff]
编辑:每个进程的“id(share.value)”都不同。但是,如果我尝试使用双精度作为共享变量,它们是相同的,并且它的工作方式就像一个魅力。这可能是 python 的 bug 吗?
在我看来,在进程之间共享项目的最佳方式是管道(本文是一个很好的资源:https://superfastpython.com/multiprocessing-pipe-in-python/)。
基本上,管道在两个(且只有两个)进程之间来回发送字符串(您可以通过将所有内容通过管道传输到基于标签中继消息的“交换机”进程来解决此问题)。
这里是 API 的快速概述
# Create Pipe
from multiprocessing import Pipe
frontend_pipe, backend_pipe = Pipe()
# Send string
frontend_pipe.send("Example: instructions can also be parsed using str.split(': ')")
# Recieve string
string = backend_pipe.recv()
# Two-way communication
backend_pipe.send("Finished")
pipe.recv() 方法将阻塞事件循环,直到收到字符串。
为什么这是我的首选方法是任何可以腌制的对象也可以使用 Pipe.send_bytes() 和 pipeline.recv_bytes() 在使用 Pipe 的对象之间共享。