扫码关注官方订阅号
python 多线程读取同一个文本,怎样解决资源竞争呢?文本形式为每行一个字符串数据。 补充:比如5个线程同时读取同一个文本,怎样让每个线程读取的内容不重复
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
可以把文件描述符当做临界资源,代码如下:
#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
Locks also support the context manager protocol.
最简单的策略就是用“锁”了,可以看下fcntl。
一起读不用加锁。。。又不是写
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
可以把文件描述符当做临界资源,代码如下:
谢谢题主,因为这道题,我看到了
Locks also support the context manager protocol.http://docs.python.org/3.3/library/threading.html?highlight=lock#lock-objects
最简单的策略就是用“锁”了,可以看下fcntl。
一起读不用加锁。。。又不是写