本篇文章主要介紹了python多執行緒之事件Event的使用詳解,現在分享給大家,也為大家做個參考。一起來看看吧
前言
小夥伴a,b,c圍著吃火鍋,當菜上齊了,請客的主人說:開吃! ,於是小夥伴一起動筷子,這種場景如何實作
Event(事件)
Event(事件):事件處理的機制:全域定義了內建標誌Flag,如果Flag值為False,那麼當程式執行event.wait方法時就會阻塞,如果Flag值為True,那麼event.wait 方法時便不再阻塞。
Event其實就是一個簡化版的 Condition。 Event沒有鎖,無法使執行緒進入同步阻塞狀態。
Event()
set(): 將標誌設為True,並通知所有處於等待阻塞狀態的執行緒復原執行狀態。
clear(): 將標誌設為False。
wait(timeout): 如果標誌為True將立即傳回,否則阻塞執行緒至等待阻塞狀態,等待其他執行緒呼叫set()。
isSet(): 取得內建標誌狀態,傳回True或False。
Event案例1
場景:小夥伴a和b準備就緒,當收到通知event.set ()的時候,會執行a和b執行緒
# coding:utf-8 import threading import time event = threading.Event() def chihuoguo(name): # 等待事件,进入等待阻塞状态 print '%s 已经启动' % threading.currentThread().getName() print '小伙伴 %s 已经进入就餐状态!'%name time.sleep(1) event.wait() # 收到事件后进入运行状态 print '%s 收到通知了.' % threading.currentThread().getName() print '小伙伴 %s 开始吃咯!'%name # 设置线程组 threads = [] # 创建新线程 thread1 = threading.Thread(target=chihuoguo, args=("a", )) thread2 = threading.Thread(target=chihuoguo, args=("b", )) # 添加到线程组 threads.append(thread1) threads.append(thread2) # 开启线程 for thread in threads: thread.start() time.sleep(0.1) # 发送事件通知 print '主线程通知小伙伴开吃咯!' event.set()
#運行結果:
##Thread- 1 已經啟動小夥伴a 已經進入用餐狀態!
Thread-2 已經啟動
小夥伴 b 已經進入用餐狀態!
主執行緒通知小夥伴開吃咯!
Thread-1 收到通知了.
小夥伴 a 開始吃咯!
Thread-2 收到通知了.
小夥伴 b 開始吃咯!
Event案例2
場景:當小夥伴a,b,c集結完畢後,請客的人發話:開吃咯!# coding:utf-8 import threading import time event = threading.Event() def chiHuoGuo(name): # 等待事件,进入等待阻塞状态 print '%s 已经启动' % threading.currentThread().getName() print '小伙伴 %s 已经进入就餐状态!'%name time.sleep(1) event.wait() # 收到事件后进入运行状态 print '%s 收到通知了.' % threading.currentThread().getName() print '%s 小伙伴 %s 开始吃咯!'%(time.time(), name) class myThread (threading.Thread): # 继承父类threading.Thread def __init__(self, name): '''重写threading.Thread初始化内容''' threading.Thread.__init__(self) self.people = name def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 '''重写run方法''' chiHuoGuo(self.people) # 执行任务 print("qq交流群:226296743") print("结束线程: %s" % threading.currentThread().getName()) # 设置线程组 threads = [] # 创建新线程 thread1 = myThread("a") thread2 = myThread("b") thread3 = myThread("c") # 添加到线程组 threads.append(thread1) threads.append(thread2) threads.append(thread3) # 开启线程 for thread in threads: thread.start() time.sleep(0.1) # 发送事件通知 print '集合完毕,人员到齐了,开吃咯!' event.set()運行結果:
Thread-1 已經啟動小夥伴a 已經進入用餐狀態!
#1516780957.47 小夥伴 b 開始吃咯!結束執行緒: Thread-3qq交流群組:226296743
Thread-2 已經啟動
小夥伴 b 已經進入用餐狀態!
Thread-3 已經啟動
小夥伴 c 已經進入用餐狀態!
集合完畢,人員到齊了,開吃咯!
Thread-1 收到通知了.
1516780957.47 小夥伴 a 開始吃咯!
qq交流群:226296743
結束線程: Thread-1
Thread-3 收到通知了.
1516780957.47 小夥伴 c 開始吃咯! Thread-2 收到通知了.
qq交流群:226296743結束執行緒: Thread-2
##相關推薦:
#
以上是python多執行緒之事件Event的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

使用NumPy創建多維數組可以通過以下步驟實現:1)使用numpy.array()函數創建數組,例如np.array([[1,2,3],[4,5,6]])創建2D數組;2)使用np.zeros(),np.ones(),np.random.random()等函數創建特定值填充的數組;3)理解數組的shape和size屬性,確保子數組長度一致,避免錯誤;4)使用np.reshape()函數改變數組形狀;5)注意內存使用,確保代碼清晰高效。

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增強可讀性,和Boostsperformance.Shere'shore'showitworks:1)較小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

文章討論了由於語法歧義而導致的Python中元組理解的不可能。建議使用tuple()與發電機表達式使用tuple()有效地創建元組。 (159個字符)

本文解釋了Python中的模塊和包裝,它們的差異和用法。模塊是單個文件,而軟件包是帶有__init__.py文件的目錄,在層次上組織相關模塊。

文章討論了Python中的Docstrings,其用法和收益。主要問題:Docstrings對於代碼文檔和可訪問性的重要性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版
中文版,非常好用

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具