Here's my problem: I need to perform frequently reading/writing operations to one file via different threads, and I tend to use threading.RLock().acquire() and threading.RLock().release() to lock the resource(e.g., one txt file). The thing is, you can easily do file writing operations in a certain thread, how do you get the return value in the thread? Here's my sample code:
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()
开发者_StackOverflow社区 return Content #### Obviously this won't work, but if I want to get the content in a thread, how should I code?
FileLock.release()
You should use some variable accessible both to the worker thread and to the main thread.
For example, worker thread can get as an input a reference to some object and fill it when done. Main thread will wait workers threads to finish, then will check the objects.
精彩评论