首页 > 编程语言 > 详细

Python学习笔记--threading线程

时间:2020-03-03 00:22:09      阅读:91      评论:0      收藏:0      [点我收藏+]

通过线程来实现多任务并发。提高性能。先看看例子。

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2020-03-02 21:10:39
 4 # @Author  : Flyinghappy (671474@qq.com)
 5 # @Link    : https://www.cnblogs.com/flyinghappy/
 6 # @Version : $Id$
 7 import time
 8 import threading
 9 import requests
10 import urllib.request
11 def runinfo(func):
12     def inner(*args):
13         print(开始访问---+str(args[0]))
14         start_time=time.time()
15         result=func(*args)
16         stop_time=time.time()
17         print(func.__name__+------running time is: %s% (stop_time-start_time))
18         print(结束访问---+str(args[0]))
19         return result
20     return inner
21 @runinfo
22 def taskfun(url):
23     html=urllib.request.urlopen(url).read()
24     return html
25 @runinfo 
26 def taskfun_outer(num_list):  
27     url=[
28     http://www.sina.com.cn,
29     http://www.cnr.cn,
30     http://www.hao123.com,
31     http://www.taobao.com,
32     https://www.eastmoney.com
33     ]
34     thread_list=[]
35     for i in range(len(url)):
36         t=threading.Thread(target=taskfun,args=(url[i],))
37         thread_list.append(t)
38     for item in thread_list:
39         item.start()
40     for item in thread_list:
41         item.join()
42     
43 def main():
44     start_time=time.time()
45     num_list=[taskfun_outer]
46     taskfun_outer(num_list)
47     stop_time=time.time()
48     print(main---running time is: %s% (stop_time-start_time))
49 if __name__ == __main__:
50     main()
View Code

测试结果:从用的时间看访问的任务是并发的,还可以从执行的顺序来看。

技术分享图片

 

Python学习笔记--threading线程

原文:https://www.cnblogs.com/flyinghappy/p/12398255.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!