python中的協程(協同程式)

來源:互聯網
上載者:User
協程:將函數編寫為一個能處理輸入參數的任務
使用yield語句並以運算式yield的形式建立協程
#匹配器案例:

def print_info(data):     print('Looking for',data);     while True:       line = (yield)       if data in line:         print(line);

上面這個函數 就是一個協程程式 要使用這個函數 首先需用調用它 並且 向前執行到第一條yield語句

info = print_info('python');  info.__next__();  #向前執行第一條yield語句

輸出結果:
Looking for python

然後使用send方法發送資料給協同程式進行處理

info.send('Hell world');   info.send('this is python');   info.send('python goods');

如果 發送的資料中含有data參數值 則匹配成功 返回該條資料
輸出結果:
Looking for python
this is python
python goods
send()為協程發送值時 程式處於暫時中止狀態 當發送值後 yield運算式將返回這個值,後面的程式對傳回值進行處理 直到遇到下一個運算式 結束 這個過程將持續運行直到協程函數返回或者調用close方法
基於一部分程式產生的資料會被程式的另一部分使用(生產者-使用者模式)
編寫並發程式時,協程作用很明顯 他代表資料的一個使用者

info =[      print_info('python'),      print_info('hello'),      print_info('chunrui')  ]

通過調用__next__()準備所有的匹配器

for n in info:    n.__next__();

定義一個函數擷取檔案中每列資料並且傳遞給產生器

def tail(f):     for line in f :       if not line:         time.sleep(0.1);         continue; #如果不存在 則延遲0.1s 進行下一次       yield line;  myList = tail(open('E:/work.txt'))

迴圈myList中的值 然後send給協程程式

for m in myList:    for n in info:      n.send(m);

輸出結果:

Looking for pythonLooking for helloLooking for chunruipython is conputer languagechunrui is namehello world is the first caseI like to use pythonmy name is chunrui

總結:
1,協程:協同程式 能處理輸入的參數的任務函數 當協程暫停時 我們從其中擷取到傳回值 當調用回到程式中時 能夠傳入額外或者新的參數 仍然能夠從上次離開的地方繼續

2,使用send函數為協程發送參數

以上就是python中的協程(協同程式)的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.