python concurrent programming -gevent Compendium

A, gevent achieve a certain function asynchronous concurrent

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# Date: 2019/11/30
# Author: SunXiuWen
"""pip install -i https://pypi.douban.com/simple/ gevent"""
import time
import gevent
from gevent import monkey
monkey.patch_all()


def task(i):
    time.sleep(3)
    print(i)


def work():
    g_list = [gevent.spawn(task, i) for i in range(10)]
    gevent.joinall(g_list)
    return [i.value for i in g_list]


if __name__ == '__main__':
    start = time.time()
    ret = work()
    end = time.time() - start
    print(ret, '\n', end)

    """结论:
    如果不配置monkey,则是阻塞状态,要花费30秒左右,且导入gevent模块必须在一个模块中
    """

Work applications: such as reptiles, downloading is a function f1, resolution is a function of f2, lived through the spawn, then by gevent.joinall([gevent.spawn(f1),gevent.spawn(f2)])enabling concurrent coroutines!

Guess you like

Origin www.cnblogs.com/sunxiuwen/p/12234340.html