代码之家  ›  专栏  ›  技术社区  ›  Shane

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

  •  2
  • Shane  · 技术社区  · 15 年前

    我的问题是:我需要通过不同的线程对一个文件执行频繁的读/写操作,我倾向于使用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()
    
    1 回复  |  直到 15 年前
        1
  •  0
  •   Drakosha    15 年前

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

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