如何在Python中执行频繁的文件读写操作(多线程)?

2 投票
1 回答
598 浏览
提问于 2025-04-16 07:32

我遇到的问题是:我需要通过不同的线程频繁地对一个文件进行读写操作。我打算使用 threading.RLock().acquire() 和 threading.RLock().release() 来锁定这个资源(比如一个文本文件)。问题是,在某个线程中,你可以很容易地进行文件写入操作,但你怎么能在这个线程中获取返回值呢?下面是我的示例代码:

FileLock = threading.RLock()

def FileReadingWriting(self, Input, Mode)

    #### Input: things to write
    #### Mode:    1    -    write to the file
    ####          2    -    read from the file

    FileLock.acquire()

    if Mode == 1:
        TheFile = open("example.txt", "w")
        TheFile.write(Input)
        TheFile.close()
    elif Mode == 2:
        TheFile = open("example.txt", "r")
        Content = TheFile.read()
        TheFile.close()

        return Content #### Obviously this won't work, but if I want to get the content in a thread, how should I code?

    FileLock.release()

1 个回答

0

你应该使用一些变量,这些变量可以被工作线程和主线程都访问。

比如,工作线程可以接收一个对象的引用作为输入,然后在完成任务后填充这个对象。主线程会等待工作线程完成,然后再检查这些对象。

撰写回答