線程的語法 (event,重要)

Python threading模塊

2種調用方式

直接調用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import?threading
import?time
def?sayhi(num):?#定義每個線程要運行的函數
????print("running on number:%s"?%num)
????time.sleep(3)
if?__name__?==?'__main__':
????t1?=?threading.Thread(target=sayhi,args=(1,))?#生成一個線程實例
????t2?=?threading.Thread(target=sayhi,args=(2,))?#生成另一個線程實例
????t1.start()?#啟動線程
????t2.start()?#啟動另一個線程
????print(t1.getName())?#獲取線程名
????print(t2.getName())

繼承式調用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import?threading
import?time
class?MyThread(threading.Thread):
????def?__init__(self,num):
????????threading.Thread.__init__(self)
????????self.num?=?num
????def?run(self):#定義每個線程要運行的函數
????????print("running on number:%s"?%self.num)
????????time.sleep(3)
if?__name__?==?'__main__':
????t1?=?MyThread(1)
????t2?=?MyThread(2)
????t1.start()
????t2.start()

?第二種有點傻

基本語法

is_alive() 當前活躍的線程

例子:

car1 = threading.Thread(target=car,args=('bmw',))
car1.start()
print(car1.is_alive())
if car1.is_alive():print('33')
if not car1.is_alive():print('444')

執行結果:

bmw wait red light
True
33

例子對比:

car1 = threading.Thread(target=car,args=('bmw',))
# car1.start()   注釋掉
print(car1.is_alive()) 
if car1.is_alive():print('33')
if not car1.is_alive():print('444')

執行結果:

False
444

?

Join ()

等待!其實就wait()。

等待該線程執行完畢

Daemon()

守護進程!有句話怎么說來著!守護進程被吞噬!

# _*_coding:utf-8_*_
import time
import threadingstart_time=time.time()
def run(n):print('[%s]------running----\n' % n)time.sleep(2)print('--done--%s'%n)def run2(n):print('[%s]------running----\n' % n)time.sleep(5)print('--done--%s'%n)
lis_1=[]
t1 = threading.Thread(target=run, args=('run%1',))
t2 = threading.Thread(target=run2, args=('run%2',))lis_1.append(t1)
lis_1.append(t2)
# t2.setDaemon(True)# 將main線程設置為Daemon線程,它做為程序主線程的守護線程,當主線程退出時,m線程也會退出,由m啟動的其它子線程會同時退出,不管是否執行完任務
t1.start()
t2.start()
#  看下就懂了,不懂試一試就想起來了
t1.join()
t2.join()print("---end time----",time.time()-start_time)

?

線程鎖(互斥鎖Mutex)

lock()

為什么上鎖?因為好多線程同時修改一個數據,有先后順序,有的沒干完,就被gil了,所以對修改數據的地方加把鎖,保證該數據的正確性!

lock?=?threading.Lock()?#生成全局鎖

不帶鎖例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import?time
import?threading
def?addNum():
????global?num?#在每個線程中都獲取這個全局變量
????print('--get num:',num )
????time.sleep(1)
????num??-=1?#對此公共變量進行-1操作
num?=?100??#設定一個共享變量
thread_list?=?[]
for?i?in?range(100):
????t?=?threading.Thread(target=addNum)
????t.start()
????thread_list.append(t)
for?t?in?thread_list:?#等待所有線程執行完畢
????t.join()
print('final num:', num )

?

帶鎖例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import?time
import?threading
def?addNum():
????global?num?#在每個線程中都獲取這個全局變量
????print('--get num:',num )
????time.sleep(1)
????lock.acquire()?#修改數據前加鎖
????num??-=1?#對此公共變量進行-1操作
????lock.release()?#修改后釋放
num?=?100??#設定一個共享變量
thread_list?=?[]
lock?=?threading.Lock()?#生成全局鎖
for?i?in?range(100):
????t?=?threading.Thread(target=addNum)
????t.start()
????thread_list.append(t)
for?t?in?thread_list:?#等待所有線程執行完畢
????t.join()
print('final num:', num )

RLock(遞歸鎖)

這個主要針對函數甲里邊包涵函數乙,函數乙又有函數丙

繞進去了,很麻煩,用lock的話容易死循環,所以用Rlock,一鍵上鎖,保證不亂。例子看看就好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import?threading,time
def?run1():
????print("grab the first part data")
????lock.acquire()
????global?num
????num?+=1
????lock.release()
????return?num
def?run2():
????print("grab the second part data")
????lock.acquire()
????global??num2
????num2+=1
????lock.release()
????return?num2
def?run3():
????lock.acquire()
????res?=?run1()
????print('--------between run1 and run2-----')
????res2?=?run2()
????lock.release()
????print(res,res2)
if?__name__?==?'__main__':
????num,num2?=?0,0
????lock?=?threading.RLock()
????for?i?in?range(10):
????????t?=?threading.Thread(target=run3)
????????t.start()
while?threading.active_count() !=?1:
????print(threading.active_count())
else:
????print('----all threads done---')
????print(num,num2)

Semaphore(信號量)

互斥鎖 同時只允許一個線程更改數據,而Semaphore是同時允許一定數量的線程更改數據 ,比如廁所有3個坑,那最多只允許3個人上廁所,后面的人只能等里面有人出來了才能再進去。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import?threading,time
def?run(n):
????semaphore.acquire()
????time.sleep(1)
????print("run the thread: %s\n"?%n)
????semaphore.release()
if?__name__?==?'__main__':
????num=?0
????semaphore??=?threading.BoundedSemaphore(5)?#最多允許5個線程同時運行
????for?i?in?range(20):
????????t?=?threading.Thread(target=run,args=(i,))
????????t.start()
while?threading.active_count() !=?1:
????pass?#print threading.active_count()
else:
????print('----all threads done---')
????print(num)

?

Events ?

重點,標識符,event可以理解成對全局變量不停的修改,!!!!!!這個我感覺后邊能用的到,用event來驗證result

語法有

event = threading.Event()

創建標識符

?

event.set( )

設置標識符

?

event.wait( )

等待標識符出現,一旦出現立刻執行后邊的代碼

print(‘殺啊!!’)
event.wait()
print( ‘撤退!!,殺個瘠薄’

?

event.clear( )

清空標志位

通過Event來實現兩個或多個線程間的交互

紅綠燈例子!!

import time
import threadingevent=threading.Event()def car(name):while True:if event.is_set():print('%s is runing'%name)time.sleep(1)else:print('%s wait red light' % name)event.wait()time.sleep(1)def light():conent = 0event.set()while True:if conent >5 and conent <10:event.clear()print('\033[41;1mred light is on ....\033[0m')elif conent >10:event.set()conent = 0else:print('\033[42;1mgreen is come!\033[0m')time.sleep(1)conent += 1light = threading.Thread(target=light,)car2 = threading.Thread(target=car,args=('tesla',))car1 = threading.Thread(target=car,args=('bmw',))
light.start()
car1.start()
car2.start()

運行結果

?

轉載于:https://www.cnblogs.com/PYlog/p/9240692.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/280005.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280005.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280005.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

求最大值和下標值

本題要求編寫程序&#xff0c;找出給定的n個數中的最大值及其對應的最小下標&#xff08;下標從0開始&#xff09;。 輸入格式: 輸入在第一行中給出一個正整數n&#xff08;1<n≤10&#xff09;。第二行輸入n個整數&#xff0c;用空格分開。 輸出格式: 在一行中輸出最大值及…

windows應用商店修復_如何修復Windows應用商店中的卡死下載

windows應用商店修復Though it’s had its share of flaky behavior since being introduced in Windows 8, the Windows Store has gotten more reliable over time. It still has the occasional problems, though. One of the more irritating issues is when an app update…

OpenWrt:Linux下生成banner

Linux下有三個小工具可以生成banner&#xff1a;1、banner使用#生成banner&#xff1b;2、figlet使用一些普通字符生成banner&#xff1b;3、toilet使用一些復雜的彩色特殊字符生成banner。使用apt-get安裝的時候需要輸入以下命令&#xff1a; $ sudo apt-get install sysvbann…

新冠病毒中招 | 第二天

今天跟大家分享我個人感染奧密克戎毒株第二天的經歷和感受。早上7點多自然醒來&#xff0c;已經沒有四肢乏力的感覺&#xff0c;但是身體的本能還是告訴我不愿意動彈。由于第一天躺著睡了一天&#xff0c;確實是躺得腰酸背疼的。起床量了一下體溫36.4正常&#xff0c;決定今天不…

輸出到Excel

HSSFWorkbook oBook new HSSFWorkbook(); NPOI.SS.UserModel.ISheet oSheet oBook.CreateSheet(); #region 輸出到Excel MemoryStream ms new MemoryStream(); oBook.Write(ms);string sExportPath ""; using (SaveFileDialog saveFileDialog1 new SaveFileDial…

JavaScript 精粹 基礎 進階(5)數組

轉載請注明出處 原文連接 blog.huanghanlian.com/article/5b6… 數組是值的有序集合。每個值叫做元素&#xff0c;每個元素在數組中都有數字位置編號&#xff0c;也就是索引。JS中的數組是弱類型的&#xff0c;數組中可以含有不同類型的元素。數組元素甚至可以是對象或其它數組…

icloud 購買存儲空間_如何釋放iCloud存儲空間

icloud 購買存儲空間Apple offers 5 GB of free iCloud space to everyone, but you’ll run up against that storage limit sooner than you’d think. Device backups, photos, documents, iCloud email, and other bits of data all share that space. Apple為每個人提供5 …

基于LAMP實現web日志管理查看

前言&#xff1a;日志是一個重要的信息庫&#xff0c;如何高效便捷的查看系統中的日志信息&#xff0c;是系統管理員管理系統的必備的技術。實現方式&#xff1a;1、將日志存儲于數據庫。2、采用LAMP架構&#xff0c;搭建PHP應用&#xff0c;通過web服務訪問數據庫&#xff0c;…

WPF效果第二百零七篇之EditableSlider

前面簡單玩耍一下快速黑白灰效果; 今天又玩了一下ZoomBlurEffect,來看看最終實現的效果:1、ps和cs文件都在Shazzam中,咱們自己隨意玩耍;今天主角是下面這位:2、來看看自定義控件布局(TextBox、Slider、ToggleButton)&#xff1a;3、點擊編輯按鈕,我就直接偷懶了:private void E…

閑話高并發的那些神話,看京東架構師如何把它拉下神壇

轉載:閑話高并發的那些神話&#xff0c;看京東架構師如何把它拉下神壇 高并發也算是這幾年的熱門詞匯了&#xff0c;尤其在互聯網圈&#xff0c;開口不聊個高并發問題&#xff0c;都不好意思出門。高并發有那么邪乎嗎&#xff1f;動不動就千萬并發、億級流量&#xff0c;聽上去…

c# Clone方法

clone是深拷貝&#xff0c;copy是淺拷貝&#xff0c;如果是值類型的話是沒什么區別的&#xff0c;如果是引用類型的話深拷貝拷貝的事整個對象的數據&#xff0c;而淺拷貝僅僅拷貝對象的引用。因為類的實例是引用類型&#xff0c;要想用原有的類中的實例的數據的話&#xff0c;既…

使用MyQ打開車庫門時如何接收警報

Chamberlain’s MyQ technology is great for opening and closing your garage door remotely with your smartphone, but you can also receive alerts whenever your garage door opens and closes (as well as receive alerts when it’s been open for an extended amount…

踏實工作,實現價值

工作&#xff0c;為實現自我價值 若想在漫長的職場生涯中穩步高升&#xff0c;首先要踏踏實實&#xff0c;專心致志、充滿激情的去完成工作中的每一項任務&#xff0c;無論工作是繁重的還是瑣碎的&#xff0c;都要嚴格要求自己全身心的去完成。而不是一味的抱怨&#xff0c;一味…

mac 防火墻禁止程序聯網_如何允許應用程序通過Mac的防火墻進行通信

mac 防火墻禁止程序聯網If you use a Mac, chances are you might not even realize that OS X comes with a firewall. This firewall helps ensure unauthorized app and services can’t contact your computer, and prevents intruders from sniffing out your Mac on a ne…

WPF-22 基于MVVM員工管理-02

我們接著上一節&#xff0c;這節我們實現crud操作&#xff0c;我們在EmployeeViewMode類中新增如下成員&#xff0c;并在構造函數中初始化該成員code snippetpublic EmployeeViewMode() {employeeService new EmployeeService();BindData();Employee new Employee();AddComma…

linux 3

-- Linux -- 開心的一天 vi   所有的 unix like 系統都會內置 vi 文本編輯器 vim  較多使用的,可以主動的以字體顏色辨別語法的正確性&#xff0c;方便程序設計 vi/vim 的使用 -- 命令模式&#xff08;Command mode&#xff09; 輸入模式&#xff08;Insert mode&#x…

從零開始搭建一個簡單的ui自動化測試框架02(pytest+selenium+allure)

二、先搭一個架子 在我還是小白連py語法都不太熟悉的時候&#xff0c;經常在網上看關于自學ui自動化測試的博客&#xff0c;最熟悉的套路莫過于先給你介紹一下selenium的各個api&#xff0c;然后寫一套代碼去登陸微博或者百度什么的&#xff0c;但我今天不愿意這么寫&#xff0…

DML語言DDL

DML&#xff08;data manipulation language&#xff09;&#xff1a; 它們是SELECT、UPDATE、INSERT、DELETE&#xff0c;就象它的名字一樣&#xff0c;這4條命令是用來對數據庫里的數據進行操作的語言 。 DDL&#xff08;data definition language&#xff09;&#xff1a; D…

什么是Adobe Lightroom,我需要它嗎?

Adobe Photoshop Lightroom confuses a lot of new photographers. It has Photoshop in the name, but it isn’t Photoshop? What gives? Adobe Photoshop Lightroom使許多新攝影師感到困惑。 它的名稱是Photoshop&#xff0c;但不是Photoshop嗎&#xff1f; 是什么賦予了&…

jquery中的serializeArray方法的使用

轉載于:https://blog.51cto.com/11871779/2359556