2010-11-24 478 views
2

這是我的問題:我需要經常通過不同的線程對一個文件執行讀/寫操作,並且我傾向於使用threading.RLock()。acquire()和threading.RLock()。release()來鎖定資源(例如,一個txt文件)。事情是,你可以很容易地在某個線程中執行文件寫入操作,你如何獲得線程中的返回值?這裏是我的示例代碼:如何在Python中執行頻繁的文件讀/寫操作(多線程)?

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

回答

0

您應該使用一些變量可以訪問工作線程和主線程。

例如,工作線程可以獲得對某個對象的引用並在完成時填充它。主線程將等待工作線程完成,然後檢查對象。

相關問題