#协程, also known as micro-threading, is a lightweight thread of user-state
#!usr/bin/env python
#-*-Coding:utf-8-*-
__author__ = "Samson"
#greenlet是协程 "Manual Stop Switching"
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是协程 "Auto block toggle"
Import Gevent
def foo ():
Print ("Running in foo")
Gevent.sleep (2) #模仿io操作
Print ("Explicit context SWITC H to foo again ")
def Bar ():
Print (" Explicit precise context content to bar ")
Gevent.sleep (1) # mimic IO operation
Print ("Implicit context switch back to bar")
Gevent.joinall ([
Gevent.spawn (foo),
Gevent . Spawn (bar),
])
co-crawler
#!usr/bin/env python
#-*-Coding:utf-8-*-
__author__ = "Samson"
From Urllib Import Request
Import Gevent,time
From gevent Import Monkey
Monkey.patch_all () #将当前所有程序io操作单独做上标记 so that the crawler can be used in a co-process mode, otherwise it will be serial
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 ("Sync 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 ("HS Cost", Time.time ()-async_time_start)
Python: Co-process