如何将两个对象连接到一个圆形(最好是动态调整大小)缓冲区,该缓冲区可以被视为管道或套接字的两侧?也就是说,一个对象可以从某个fifo缓冲区读取并关闭读取端,其他对象可以在那里写入并关闭写入端。我不需要任何投票/选择功能。
一个进程,一个线程。不涉及IPC或同步。(这已经单独实现了。)
它们应该充当来自其他来源的数据的适配器,这些来源不是类似文件的对象,但可以表示为流。
如果我用手写的话,我会觉得我发明了一个轮子。
也许io模块的一些类组合可以做到这一点。有没有跨平台的操作系统级的fifo/管道对象?
解决方案必须是内存高效的。
发布于 2018-12-20 21:03:40
真正的跨平台管道具有实际的文件句柄,甚至可以用子进程使用,它是multipricessing.Pipe并使用其文件描述符:
import multiprocessing
import os
conn_out, conn_in = multiprocessing.Pipe(duplex=False)
os.write(conn_in.fileno(), b'Hello.')
print(os.read(conn_out.fileno(), 10))请注意,multipricessing.Pipe.send和multipricessing.Pipe.recv方法使用字节操作,multipricessing.Pipe.send_bytes和multipricessing.Pipe.recv_bytes方法添加头部。
发布于 2018-06-30 02:06:29
效率不是很高,但就是这样。
from collections import deque
class AlreadyClosed(Exception):
pass
class NothingToRead(Exception):
pass
def make_pipe():
queue = deque()
class Reader(object):
closed = False
@staticmethod
def read():
if Reader.closed:
raise AlreadyClosed()
if Writer.closed:
return b''
try:
return queue.popleft()
except IndexError:
raise NothingToRead()
class Writer(object):
closed = False
@staticmethod
def write(chunk):
if Writer.closed:
raise AlreadyClosed()
if Reader.closed:
return 0
queue.append(chunk)
return len(chunk)
return Reader, Writer
if __name__ == '__main__':
r, w = make_pipe()
w.write(b'qwe')
w.write(b'asd')
print(r.read())
print(r.read())
try:
print(r.read())
except NothingToRead as e:
print(repr(e))https://stackoverflow.com/questions/51106648
复制相似问题