如何从多个线程读/写tempfile

2024-09-30 16:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文:

操作系统:Windows 8.1

python——版本:python2.7.8

我试图从一个流读/写,并使用一个线程写入该流,另一个线程从中读取写入的新数据位。我使用tempfile模块,用一种方法向其写入二进制数据,另一种方法从中读取。在

在下面的代码中,t1运行写入,t2运行reading thread方法。t3和t4出口使t1和t2环路退出。在

我的预期结果是:

READ @0: 0|1|2|3|.........|N    --- L Bytes read
READ @L: N|N+1|N+2|.......|M    --- J Bytes read
READ @L+J: M|M+1|M+3|.....|P    --- K Bytes read
READ @L+J+K:                    --- 0 Bytes read (nothing was written by write thread)

以此类推,当tempfile中有更多数据时,它就会被读取和输出,但与此同时,写入必须由另一个线程进行,以便写入从流接收到的数据。在

问题:

当我运行它时,我得到的输出会变化 接收到的输出之一:

^{pr2}$

另一个输出:

> python.exe tmp.py
READ @ 0 :  0|289721|289722|...[truncated output]...289718|28971
Exception in thread Thread-1:
Traceback (most recent call last):
  [truncated output]
    self.myf.write(str(self.current_count)+"|")
IOError: [Errno 0] Error

其他输出或多或少是上述输出的变化。在

我认为这个问题是由于文件描述符指针被读操作改变了,但是我认为append总是写到文件末尾。在

源代码

下面是流的实际代码的抽象,流是从一个子进程stdio读取并写入另一个子进程stdio的二进制数据流。在

import threading, tempfile
class MultipleThreadTIO:
    def __init__(self):
        self.myf = tempfile.TemporaryFile(mode='a+b')
        self.current_count = 0
        self.do_write = True
        self.do_read = True

    def write_temp(self):
        while self.do_write:
            self.myf.write(str(self.current_count)+"|")
            self.current_count += 1

    def read_temp(self):
        read_at = 0L
        while self.do_read:
            self.myf.seek(read_at)
            d = self.myf.read()
            if len(d.strip()) > 0:
                print "READ @",read_at,": ", self.myf.read()
            read_at = self.myf.tell()

    def stop_write(self):
        self.do_write = False

    def stop_read(self):
        self.do_read = False

    def __del__(self):
        #self.myf.seek(0)
        #print ":::DATA CONTENT:::\n"
        #print self.myf.read()
        #print ":::END DATA CONTENT:::"
        self.myf.close()

mtio = MultipleThreadTIO()

t1 = threading.Timer(0.1, mtio.write_temp)
t2 = threading.Timer(0.5, mtio.read_temp)

t3 = threading.Timer(5, mtio.stop_write)
t4 = threading.Timer(3, mtio.stop_read)

t1.start()
t2.start()
t3.start()
t4.start()

问题:

问题1:以上问题有什么解决办法吗?在

问题2:我应该使用队列吗/os.管道(/其他?)而不是临时文件?在

问题3:有没有其他更好的办法来解决这种情况?在

重要:解决方案必须是跨平台的。在


Tags: selfreadbytesdefcountcurrenttempfiledo
1条回答
网友
1楼 · 发布于 2024-09-30 16:21:21

这是一个使用^{}的抽象,我认为如果使用队列/管道行为,这会更好。我不知道你在写什么,所以我只是把运行计数器添加到队列中。使用^{}停止对队列的写入,并通过发送停止消息停止从队列中读取数据(但如果需要更精细的控制,可以添加信号):

import threading
import Queue

class MultipleThreadTIO:
    def __init__(self):
        self.queue = Queue.Queue()
        self.current_count = 0
        self.stop_write = threading.Event()

    def write_temp(self):
        while not self.stop_write.isSet():
            self.queue.put(str(self.current_count)+"|")
            self.current_count += 1
        self.stop()

    def read_temp(self):
        while True:
            msg = self.queue.get()
            if msg == 'close':
                break
            else:
                print "READ @: " + msg

    def stop(self):
        self.queue.put('close')

mtio = MultipleThreadTIO()

t1 = threading.Timer(0.1, mtio.write_temp)
t2 = threading.Timer(0.5, mtio.read_temp)


t1.start()
t2.start()

t3 = threading.Timer(5, mtio.stop_write.set)

t3.start()

我不能在windows上测试,但我认为它应该可以工作,因为这是相当标准的。它运行在Ubuntu14.04x86_64上

相关问题 更多 >