Python学习笔记--threading线程
2024-08-30 13:40:21
通过线程来实现多任务并发。提高性能。先看看例子。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-03-02 21:10:39
# @Author : Flyinghappy (671474@qq.com)
# @Link : https://www.cnblogs.com/flyinghappy/
# @Version : $Id$
import time
import threading
import requests
import urllib.request
def runinfo(func):
def inner(*args):
print('开始访问---'+str(args[0]))
start_time=time.time()
result=func(*args)
stop_time=time.time()
print(func.__name__+'------running time is: %s'% (stop_time-start_time))
print('结束访问---'+str(args[0]))
return result
return inner
@runinfo
def taskfun(url):
html=urllib.request.urlopen(url).read()
return html
@runinfo
def taskfun_outer(num_list):
url=[
'http://www.sina.com.cn',
'http://www.cnr.cn',
'http://www.hao123.com',
'http://www.taobao.com',
'https://www.eastmoney.com'
]
thread_list=[]
for i in range(len(url)):
t=threading.Thread(target=taskfun,args=(url[i],))
thread_list.append(t)
for item in thread_list:
item.start()
for item in thread_list:
item.join() def main():
start_time=time.time()
num_list=['taskfun_outer']
taskfun_outer(num_list)
stop_time=time.time()
print('main---running time is: %s'% (stop_time-start_time))
if __name__ == '__main__':
main()
测试结果:从用的时间看访问的任务是并发的,还可以从执行的顺序来看。
最新文章
- 数据库中的two phase locking
- 深入理解javascript原型和闭包(10)——this
- 谈事件冒泡(Bubble)和事件捕捉(capture)
- 【代码笔记】iOS-scrollerView里多个tableView加搜索框
- inline-block 前世今生
- 局域网内sqldeveloper客户端连接oracle服务器
- sublime text帮你更好的写python
- 分享一个在线生成微信跳转链接实现微信内跳转浏览器打开URL的工具
- [django]date类型和datetime类型过滤
- Cracking The Coding Interview 9.7
- .Net Discovery系列之十一-深入理解平台机制与性能影响 (中)
- chapter1 初识Go语言
- OpenCV学习(30) 轮廓defects
- BurpSuite 激活破解
- 【C++】new和delete表达式与内存管理
- Linux SCIM/fcitx/ibus 输入法
- hadoop MapReduce辅助排序解析
- python实战===itchat
- 关于springboot 打包问题 jar包和 war包
- windows下 安装python_ldap MySQL-python