鱼C论坛

 找回密码
 立即注册
查看: 1938|回复: 0

[技术交流] 学习多线程,同时打印多个文件内容

[复制链接]
发表于 2020-5-27 14:51:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Cool_Breeze 于 2020-5-27 14:53 编辑
  1. #!/usr/bin/env python3
  2. #coding=utf-8

  3. from time import time
  4. import threading
  5. #列表长度觉得开启线程数量
  6. loops = ['1.txt','2.txt']

  7. #派生Thread的子类
  8. class threadFunc(threading.Thread):
  9.     def __init__(self,func,args,name=''):
  10.         threading.Thread.__init__(self)
  11.         self.func = func
  12.         self.args = args
  13.         self.name = name
  14.     def run(self):
  15.         self.func(*self.args)

  16. def loop(name):
  17.     with open(name,'r') as f:
  18.         for line in f:
  19.             if '\n' in line:
  20.                 print (name,' :',line,end='')
  21.             else:
  22.                 print (name,' :',line)
  23.    
  24. def main():
  25.     print('starting at:',time())
  26.     #线程锁
  27.     threadkey = []
  28.     nloops = range(len(loops))
  29.    
  30.     for i in nloops:
  31.         #get线程锁
  32.         #创建子类的实例
  33.         t = threadFunc(loop,(loops[i],),loop.__name__)
  34.         threadkey.append(t)
  35.    
  36.     #开启线程
  37.     for i in nloops:
  38.         threadkey[i].start()
  39.     #等待所有线程结束
  40.     for i in nloops:
  41.         threadkey[i].join()
  42.         
  43.     print('All Done at:',time())
  44.    
  45. if __name__ == '__main__':
  46.     main()
复制代码
  1. starting at: 1590562220.892479
  2. 1.txt  : 1005495524----a111111
  3. 1.txt  : 1005495524----abc123
  4. 2.txt  : 1111qqqq1111---a111111
  5. 1.txt  : 1005495524----aini1314
  6. 2.txt  : 1111qqqq1111---abc123
  7. 1.txt  : 1005495524----iloveyou
  8. 2.txt  : 1111qqqq1111---aini1314
  9. 1.txt  : 1005495524----q1w2e3r4
  10. 2.txt  : 111qqq111---a111111
  11. 1.txt  : 1005495524----qq123123
  12. 2.txt  : 111qqq111---abc123
  13. 2.txt  : 111qqq111---aini1314
  14. All Done at: 1590562220.892479

  15. 请按任意键继续. . .
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-20 11:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表