Skip to main content
 首页 » 编程设计

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

2025年05月04日19powertoolsteam

这是我的问题:我需要通过不同的线程对一个文件执行频繁的读/写操作,我倾向于使用 threading.RLock().acquire() 和 threading.RLock().release() 来锁定文件资源(例如,一个 txt 文件)。问题是,你很容易在某个线程中进行写文件操作,你如何获取线程中的返回值?这是我的示例代码:

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() 

请您参考如下方法:

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

例如,工作线程可以获取对某个对象的引用作为输入,并在完成后填充它。主线程将等待工作线程完成,然后检查对象。