使用Python写一个多线程代码。线程1用来往文件里写内容,线程2从文件里读内容。需要保持两个线程之间同步
时间: 2024-02-16 21:05:03 浏览: 23
好的,我可以为您提供一个示例代码。
```python
import threading
class FileOperation:
def __init__(self):
self.file = 'test.txt'
self.lock = threading.Lock()
def write_file(self, content):
with self.lock:
with open(self.file, 'a') as f:
f.write(content + '\n')
def read_file(self):
with self.lock:
with open(self.file, 'r') as f:
content = f.read()
return content
def writer(file_operation, content):
file_operation.write_file(content)
def reader(file_operation):
content = file_operation.read_file()
print(content)
if __name__ == '__main__':
file_operation = FileOperation()
thread1 = threading.Thread(target=writer, args=(file_operation, 'hello'))
thread2 = threading.Thread(target=reader, args=(file_operation,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
```
在这个代码中,我们定义了一个 FileOperation 类,它包含一个文件名和一个锁。write_file() 方法用于向文件中写入内容,read_file() 方法用于从文件中读取内容。在两个方法中,我们都使用了锁来保证线程之间的同步。在 main 函数中,我们创建了两个线程,一个用于写文件,一个用于读文件。最后我们使用 join() 方法来等待两个线程执行完成。