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