1. 程式人生 > >協程+IO切換實現並發

協程+IO切換實現並發

page pri org 切換 key let url gree github

from gevent import monkey
# 以後代碼中遇到IO都會自動執行greenlet的switch進行切換
monkey.patch_all() 
import requests
import gevent


def get_page1(url):
    ret = requests.get(url)
    print(url,ret.content)

def get_page2(url):
    ret = requests.get(url)
    print(url,ret.content)

def get_page3(url):
    ret = requests.get(url)
    print(url,ret.content)

gevent.joinall([
    gevent.spawn(get_page1, 'https://www.python.org/'), # 協程1
    gevent.spawn(get_page2, 'https://www.yahoo.com/'),  # 協程2
    gevent.spawn(get_page3, 'https://github.com/'),     # 協程3
])

協程+IO切換實現並發