python 多线程读取同一个文本,怎样解决资源竞争呢?文本形式为每行一个字符串数据。
补充:比如5个线程同时读取同一个文本,怎样让每个线程读取的内容不重复
最简单的策略就是用“锁”了,可以看下fcntl。
一起读不用加锁。。。又不是写
可以把文件描述符当做临界资源,代码如下:
#python3
import threading
import time
mutex = threading.Lock()
fp = open('content')
class Reader(threading.Thread):
def __init__(self, num):
super().__init__()
self.num = num
def run(self):
while True:
with mutex:
line = fp.readline()
if len(line) == 0:
return
print('%d:%s' % (self.num, line), end='')
time.sleep(0.1)
if __name__ == '__main__':
r1 = Reader(1)
r2 = Reader(2)
r1.start()
r2.start()
r1.join()
r2.join()
谢谢题主,因为这道题,我看到了Locks also support the context manager protocol.
http://docs.python.org/3.3/library/threading.html?highlight=lock#lock-objects