Python教程

Python---协程

本文主要是介绍Python---协程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Python从入门到高手(内部资源-配学习资料)_哔哩哔哩_bilibili

# 协程:微线程
# 进程>线程>协程

# Process Thread 协程生成器
''':cvar
协程:耗时操作
耗时操作:网络请求 网络下载(爬虫),IO:文件的读写
'''
import time


def task1():
    for i in range(3):
        print('A' + str(i))
        yield
        time.sleep(2)


def task2():
    for i in range(3):
        print('B' + str(i))
        yield
        time.sleep(1)


if __name__ == '__main__':
    g1 = task1()
    g2 = task2()
    while True:
        try:
            next(g1)
            next(g2)
        except:
            break

----------------------------------------------------------------------------------------------------------------

# greenlet 完成协程任务
import time

from greenlet import greenlet


def a():  # 任务A
    for i in range(5):
        print("A" + str(i))
        gb.switch()
        time.sleep(0.1)


def b():  # 任务B
    for i in range(5):
        print("B" + str(i))
        gc.switch()
        time.sleep(0.1)


def c():  # 任务C
    for i in range(5):
        print("C" + str(i))
        ga.switch()
        time.sleep(0.1)


if __name__ == '__main__':
    ga = greenlet(a)
    gb = greenlet(b)
    gc = greenlet(c)

    ga.switch()
'''A0
B0
C0
A1
B1
C1
A2
B2
C2
A3
B3
C3
A4
B4
C4'''

-------------------------------------------------------------------------------------------------------------------

# greenlet 完成协程任务
import time

import gevent
from gevent import monkey

monkey.patch_all()



def a():  # 任务A
    for i in range(5):
        print("A" + str(i))
        time.sleep(0.1)


def b():  # 任务B
    for i in range(5):
        print("B" + str(i))
        time.sleep(0.1)


def c():  # 任务C
    for i in range(5):
        print("C" + str(i))
        time.sleep(0.1)


if __name__ == '__main__':
    g1 = gevent.spawn(a)
    g2 = gevent.spawn(b)
    g3 = gevent.spawn(c)
    g1.join()
    g2.join()
    g3.join()

---------------------------------------------------------------------------------------------------------------------

import requests
import gevent
from gevent import monkey


def download(url):
    response = requests.get(url)
    content = response.text
    print('下载了{}的数据,长度:{}'.format(url, len(content)))


if __name__ == '__main__':
    urls = ['http://www.163.com', 'http://www.qq.com', 'http://www.baidu.com']
    g1 = gevent.spawn(download, urls[0])
    g2 = gevent.spawn(download, urls[1])
    g3 = gevent.spawn(download, urls[2])
    g1.join()
    g2.join()
    g3.join()
    # gevent.joinall(g1, g2, g3) 类似
这篇关于Python---协程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!