Python多線程的threading Event

來源:互聯網
上載者:User

標籤:

Python threading模組提供Event對象用於線程間通訊。它提供了一組、拆除、等待用於線程間通訊的其他方法。

event它是溝通中最簡單的一個過程之中,一個線程產生一個訊號,號。Python 通過threading.Event()產生一個event對象。event對象維護一個內部標誌(標誌初始值為False),通過set()將其置為True。wait(timeout)則用於堵塞線程直至Flag被set(或者逾時,可選的),isSet()用於查詢標誌位是否為True,Clear()則用於清除標誌位(使之為False)。

  設定\清除訊號

  Event的set()方法可設定Event對象內部的訊號標誌為真,Event對象提供了isSet()方法來推斷其內部訊號標誌的狀態,使用set()方法後,isSet()方法返回True。clear()方法可清除Event對象內部的訊號標誌(設為False)。使用clear方法後。isSet()方法返回False 

 等待

 當Event對象的內部訊號標誌為False時。wait方法一直堵塞線程等待到其為真或者逾時(若提供,浮點數,單位為秒)才返回,若Event對象內部標誌為True則wait()方法馬上返回。

舉例:

下述是一段類比“client監聽並處理硬體port訊息”的程式片段:硬體port訊息發送時機是隨機的(通過random實現),read線程負責讀訊息並通知parse線程去處理。

import threading  import time  import random  L = []   def read():       count =2       while 1:           count = random.randint(0,1)           if count:               L.append('Hello, darling,I love you\n')               L.append('You are so sweet~\n')           if L:              evt.set()              print 'new rcvd sent to \'parse thread\'\n'           time.sleep(2)       print 'never here\n'          def parse():       while 1:          if evt.isSet():               evt.clear()                      print repr(len(L)) +' messages to parse:\n'               while L:                   print L.pop(0)               print 'all msg prased,sleep 2s\n'               time.sleep(2)          else:               print 'no message rcved\n'               time.sleep(2)       print 'quit parse\n'   if __name__ == '__main__':       evt = threading.Event()       R = threading .Thread(target = read)       P = threading .Thread(target = parse)       R.start()       P.start()       time.sleep(2)       R.join()       P.join()       #time.sleep(2)       print 'end'  


著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載--“http://blog.csdn.net/suipingsp”。

Python多線程的threading Event

聯繫我們

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