python:協程,python協程

來源:互聯網
上載者:User

python:協程,python協程

1,如何?在兩個函數之間的切換?

def func1():    print(l)    yield    print(3)    yielddef func2():    g =func1()    next(g)    print(2)    next(g)    print(4)func2()

2,協程

import timefrom greenlet import greenlet   # 在單線程中切換狀態的模組def eat1():    print('吃雞腿1')    g2.switch()    time.sleep(5)    print('吃雞翅2')    g2.switch()def eat2():    print('吃餃子1')    g1.switch()    time.sleep(3)    print('白切雞')g1 = greenlet(eat1)g2 = greenlet(eat2)g1.switch()

3,gevent

from gevent import monkey;monkey.patch_all()import time     # time socket urllib requestsimport gevent   # greenlet gevent在切換程式的基礎上又實現了規避IOfrom threading import current_threaddef func1():    print(current_thread().name)    print(123)    time.sleep(1)    print(456)def func2():    print(current_thread().name)   # dummythread    print('hahaha')    time.sleep(1)    print('10jq')g1 = gevent.spawn(func1)  # 遇見他認識的io會自動切換的模組g2 = gevent.spawn(func2)gevent.joinall([g1,g2])

4,效率對比

from gevent import monkey;monkey.patch_all()import time     # time socket urllib requestsimport gevent   # greenlet gevent在切換程式的基礎上又實現了規避IOdef task(args):    time.sleep(1)    print(args)def sync_func():   # 同步    for i in range(10):        task(i)def async_func(): # 非同步    g_l = []    for i in range(10):        g_l.append(gevent.spawn(task,i))   # 給寫成任務傳參數    gevent.joinall(g_l)start = time.time()sync_func()print(time.time() - start)start = time.time()async_func()print(time.time() - start)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.