python 多线程读取一个文本,相互应该如何协调,python多线程,python 多线程读取
python 多线程读取一个文本,相互应该如何协调,python多线程,python 多线程读取
python 多线程读取同一个文本,怎样解决资源竞争呢?文本形式为每行一个字符串数据。
补充:比如5个线程同时读取同一个文本,怎样让每个线程读取的内容不重复
可以把文件描述符当做临界资源,代码如下:
#python3import threadingimport timemutex = 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
最简单的策略就是用“锁”了,可以看下fcntl。
一起读不用加锁。。。又不是写
编橙之家文章,
相关内容
- Python如何调用同级文件夹中模块方法,python同级,目录结
- Python2.7.8程序都报错,SyntaxError,,>>> python h
- Django部署重启nginx提示That port is already in use是什么意思
- vim ultisnips补全问题应该如何完成配置,vimultisnips,ulti
- Python爬取ajax网页浏览器跳转请教,pythonajax,比如下面这
- python开发WEB服务中数据库链接释放应该怎么做?,pyt
- Python实现Bin二进制文件编辑工具及方式是什么,python
- redis初始化中参数的作用,redis初始化参数,看到有这样
- Python循环插入数据库失败是何原因,python何原因,def i
- Django信息时实监控推送有什么好思路,django思路,djang
评论关闭