python gevent协程学习

发布时间:2024年01月10日
import gevent
from gevent import monkey
import redis
import requests
import time
import flask
from flask import Flask
from gevent.pywsgi import WSGIServer


app = Flask(__name__)

# 打开猴子补丁,使得gevent能够在IO操作时切换任务
monkey.patch_all()

def task1():
    print("start task1")
    gevent.sleep(2)
    return "task1"

def task2():
    print("start task2")
    gevent.sleep(9)
    return "task2"

def task3(i):
    t1 = time.time()
    requests.get("http://localhost:" + str(i))
    t2 = time.time()
    return "task" + str(i) + "\t" + str(t2-t1)

def task4():
    print("start task4")
    jobs = []
    for i in [8092, 8093]:
        job = gevent.spawn(task3, i)
        jobs.append(job)
    results = gevent.joinall(jobs, timeout=2.8)

    for result in results:
        print(result.get())
    return "task4"


def main():
    # 创建协程列表
    tasks = [gevent.spawn(task1), gevent.spawn(task2), gevent.spawn(task4)]

    # 等待任务完成,设置超时时间为200ms
    #results = gevent.joinall(tasks, timeout=3)

    # 获取结果
    #results = [task.value for task in tasks if task.successful()]

    #for result in tasks:
    #    print("result\t" + result.get())

@app.route("/")
def index():
    with gevent.Timeout(1, False):
        #gevent.sleep(2)
        time.sleep(2)
    main()
    current_greenlet = gevent.getcurrent()
    print(current_greenlet)

    return "123"

if __name__ == "__main__":
    http_server = WSGIServer(('0.0.0.0', 12345), app, log=None)
    http_server.serve_forever()


  1. 这里可以看flask如何使用协程并发;
  2. 这里看协程如何超时熔断
    3
文章来源:https://blog.csdn.net/hvgdfx/article/details/135505621
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。