Python: Co-process

Source: Internet
Author: User

#协程, 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.