一、线程threading
实例1、普通线程使用
from threading import Thread
def hello():
time.sleep(1)
print('Thread---Hello World:%s' % time.time())
if __name__ == '__main__':
[i.start() for i in [Thread(target=hello) for _ in range(5)]]
实例2、接口实例
import requests
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, *args, **kwargs): # 重写__init__方法
super().__init__(*args, **kwargs) # 调用父类的__init__方法
def run(self):
url = "http://192.168.17.176:8082/login"
data = {
"username": "admin",
"password": "admin",
}
print(str(requests.post(url, data).json()) + " " + str(time.time()))
def run1(self):
print(2)
my_thread = MyThread()
my_thread.start() # 线程里面调用start就是调用run方法
[my_thread.run() for _ in range(4)]
[my_thread.run1() for _ in range(4)]
3、定义10个线程池,节省CUP资源,如果不定义线程池,那么会过渡消耗CUP
from concurrent.futures import ThreadPoolExecutor
import requests
def run():
url = "http://192.168.17.176:8082/login"
data = {
"username": "admin",
"password": "admin",
}
print(str(requests.post(url, data).json()) + " " + str(time.time()))
if __name__ == '__main__':
pool = ThreadPoolExecutor(max_workers=10, thread_name_prefix='Thread')
[pool.submit(run) for i in range(1000)]
二、协成gevent
在协成里面优点是自动分配CPU
1、普通gevent的使用
from gevent import monkey;monkey.patch_all()
import gevent
def hello():
time.sleep(1)
print('gevent---Hello World:%s' % time.time())
if __name__ == '__main__':
gevent.joinall([gevent.spawn(hello) for i in range(5)])
2、gevent使用实战的demo
from gevent import monkey;monkey.patch_all()
import time, gevent, requests
def test():
time.sleep(1)
url = "http://192.168.17.176:8082/login"
data = {
"username": "admin",
"password": "admin",
}
print(str(requests.post(url, data).json()) + " " + str(time.time()))
gevent.joinall([gevent.spawn(test) for _ in range(10)])
三、协成asyncio
1、普通asyncio的使用
async def hello():
await asyncio.sleep(1)
print('asyncio---Hello World:%s' % time.time())
if __name__ == '__main__':
asyncio.run(asyncio.wait([hello() for _ in range(5)]))
2、asyncio超时处理
import asyncio
async def aa():
# 睡眠一秒
await asyncio.sleep(1)
url = "http://192.168.17.176:8082/login"
data = {
"username": "admin",
"password": "admin",
}
print(str(requests.post(url=url, data=data).json()) + " " + str(time.time()))
async def run():
try:
# 等待超时,如果请求结果超时1.001了那么会报错
await asyncio.wait_for(aa(), timeout=1.001)
except asyncio.TimeoutError:
print("超时了")
if __name__ == '__main__':
asyncio.run(asyncio.wait([run() for _ in range(10)]))