python:协程

Posted CanSun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python:协程相关的知识,希望对你有一定的参考价值。

#协程,又称为微线程,是一种用户态的轻量级线程
#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"
#greenlet是协程"手动挡切换"
from greenlet import greenlet

def test1():
print(12)
t2.switch()#切换到协程t2
print(36)
t2.switch()

def test2():
print(48)
t1.switch()
print(60)

t1 = greenlet(test1)#启动一个协程
t2 = greenlet(test2)

t1.switch()



#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"
#greenlet是协程"自动挡切换"
import gevent

def foo():
print("Running in foo")
gevent.sleep(2)#模仿io操作
print("Explicit context switch to foo again")


def bar():
print("Explicit精确的 context内容 to bar")
gevent.sleep(1) # 模仿io操作
print("Implicit context switch back to bar")

gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])


协程之爬虫
#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"

from urllib import request
import gevent,time
from gevent import monkey

monkey.patch_all()#将当前所有程序io操作单独做上标记,这样才能用协程方式进行爬虫,否则将会是串行的

def f(url):
print("Get: %s" %url)
resp = request.urlopen(url)
data = resp.read()
print("%d bytes received from %s."%(len(data),url))

urls = ["https://www.python.org/",
"https://www.yahoo.com/",
"https://github.com/"]
time_start = time.time()
for url in urls:
f(url)
print("同步cost",time.time()-time_start)

async_time_start = time.time()
gevent.joinall([
gevent.spawn(f,"https://www.python.org/"),
gevent.spawn(f,"https://www.yahoo.com/"),
gevent.spawn(f,"https://github.com/"),
])
print("协程cost",time.time()-async_time_start)





















































































以上是关于python:协程的主要内容,如果未能解决你的问题,请参考以下文章

Python中的协程与asyncio原理

Python中的协程与asyncio原理

Python中的协程与asyncio原理

python3之协程

python协程

python协程