Python--线程threading、协成gevent、协成asyncio的简易使用

一、线程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)]))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

z千鑫

在线乞讨,行行好吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值