這篇文章將為大家詳細(xì)講解有關(guān)python線程如何創(chuàng)建和傳參,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

站在用戶的角度思考問題,與客戶深入溝通,找到寧都網(wǎng)站設(shè)計(jì)與寧都網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:
網(wǎng)站制作、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、
主機(jī)域名、
雅安服務(wù)器托管、企業(yè)郵箱。業(yè)務(wù)覆蓋寧都地區(qū)。
一.線程解釋
線程是cpu最小調(diào)度單位,一個(gè)程序中至少有一個(gè)或者多個(gè)線程(至于進(jìn)程暫時(shí)不做講解,后面文章會(huì)有詳細(xì)解釋)!在開發(fā)中使用線程可以讓程序運(yùn)行效率更高,多線程類似于同時(shí)執(zhí)行多個(gè)不同代碼塊。
二.線程創(chuàng)建和啟動(dòng)
1.導(dǎo)入線程模塊
1 2 | # 導(dǎo)入線程threading模塊
importthreading
2.創(chuàng)建線程并初始化線程
調(diào)用threading模塊中的缺省函數(shù)Thread,創(chuàng)建并初始化線程,返回線程句柄。如果對(duì)缺省函數(shù)已經(jīng)忘記的小伙伴請(qǐng)回到 python函數(shù)的聲明和定義中關(guān)于缺省參數(shù)部分復(fù)習(xí)一下。
1 2 | # 創(chuàng)建并初始化線程,返回線程句柄
t=threading.Thread(target=函數(shù)名)
3.啟動(dòng)線程
通過初始化返回的線程句柄調(diào)用start()函數(shù),啟動(dòng)線程,此時(shí)會(huì)自動(dòng)執(zhí)行在創(chuàng)建線程時(shí)target對(duì)應(yīng)的函數(shù)內(nèi)部的代碼:
綜合上面三點(diǎn),下面使用代碼對(duì)python線程thread做詳細(xì)講解:
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 39 | # !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:何以解憂
@Blog(個(gè)人博客地址): shuopython.com
@WeChat Official Account(微信公眾號(hào)):猿說python
@Github:www.github.com
@File:python_thread.py
@Time:2019/10/16 21:02
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅(jiān)持不懈地積累!
"""
# 導(dǎo)入線程threading模塊
importthreading
# 導(dǎo)入內(nèi)置模塊time
importtime
defwash_clothes():
print("洗衣服開始...")
# sleep 5 秒,默認(rèn)以秒為單位
time.sleep(5)
print("洗衣服完成...")
defclean_room():
print("打掃房間開始...")
# sleep 5 秒,默認(rèn)以秒為單位
time.sleep(5)
print("打掃房間完成...")
if__name__=="__main__":
# 創(chuàng)建線程并初始化 -- 該線程執(zhí)行wash_clothes中的代碼
t1=threading.Thread(target=wash_clothes)
# 創(chuàng)建線程并初始化 -- 該線程執(zhí)行clean_room中的代碼
t2=threading.Thread(target=clean_room)
t1.start()
t2.start()
輸出結(jié)果:
1 2 3 4 | 洗衣服開始...
打掃房間開始...
洗衣服完成...
打掃房間完成...
運(yùn)行程序可以發(fā)現(xiàn)程序從運(yùn)行開始到結(jié)束,一共耗時(shí)5秒時(shí)間!注意觀察輸出日志:
當(dāng)然你也可以按照以前的學(xué)習(xí)的內(nèi)容,先調(diào)用wash_clothes函數(shù),在調(diào)用clean_room函數(shù),同樣能輸出內(nèi)容,而耗時(shí)卻是10秒左右,示例代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 導(dǎo)入內(nèi)置模塊time
importtime
defwash_clothes():
print("洗衣服開始...")
# sleep 5 秒,默認(rèn)以秒為單位
time.sleep(5)
print("洗衣服完成...")
defclean_room():
print("打掃房間開始...")
# sleep 5 秒,默認(rèn)以秒為單位
time.sleep(5)
print("打掃房間完成...")
if__name__=="__main__":
wash_clothes()
clean_room()
輸出結(jié)果:
1 2 3 4 | 洗衣服開始...
洗衣服完成...
打掃房間開始...
打掃房間完成...
運(yùn)行程序可以發(fā)現(xiàn)程序從運(yùn)行開始到結(jié)束,一共耗時(shí)10秒時(shí)間!注意觀察輸出日志:
一:洗衣服開始;
二:程序停止了5秒;
三:洗衣服完成,打掃房間開始
四:程序停止5秒;
五:打掃房間結(jié)束,程序結(jié)束;
由此可見:多線程可以同時(shí)運(yùn)行多個(gè)任務(wù),效率遠(yuǎn)比單線程更高!
三.線程傳參
在上面的demo中,我們并沒有為線程傳遞參數(shù),如果在線程中需要傳遞參數(shù)怎么辦呢?
threading.Thread()函數(shù)中有兩個(gè)缺省參數(shù) args 和 kwargs ,args 是元組類型,kwargs 是字典類型,缺省值默認(rèn)為空,除此之外,其實(shí)還可以設(shè)置線程的名字等,其函數(shù)聲明如下:
(ps:如果對(duì)缺省函數(shù)已經(jīng)忘記的小伙伴請(qǐng)回到 python函數(shù)的聲明和定義中關(guān)于缺省參數(shù)部分復(fù)習(xí)一下)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def__init__(self,group=None,target=None,name=None,
args=(),kwargs=None,*,daemon=None):
"""This constructor should always be called with keyword arguments. Arguments are:
*group* should be None; reserved for future extension when a ThreadGroup
class is implemented.
*target* is the callable object to be invoked by the run()
method. Defaults to None, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of
the form "Thread-N" where N is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ().
*kwargs* is a dictionary of keyword arguments for the target
invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke
the base class constructor (Thread.__init__()) before doing anything
else to the thread.
"""
示例代碼如下:
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 | # 導(dǎo)入線程threading模塊
importthreading
# 導(dǎo)入內(nèi)置模塊time
importtime
defwash_clothes(*args,**kargcs):
print("wash_clothes:",args)
print("wash_clothes:",kargcs)
defclean_room(*args,**kargcs):
print("clean_room:",args)
print("clean_room:",kargcs)
if__name__=="__main__":
t1=threading.Thread(target=wash_clothes,
args=(1,"猿說python"), # args 傳遞元組,可以同時(shí)傳遞多個(gè)數(shù)據(jù)
kwargs={"a":1,"b":False})# kwargs 傳遞字典,可以同時(shí)傳遞多個(gè)鍵值對(duì)
t2=threading.Thread(target=clean_room,
args=(2,False),# args 傳遞元組,可以同時(shí)傳遞多個(gè)數(shù)據(jù)
kwargs={"c":0.2,"d":False})# kwargs 傳遞字典,可以同時(shí)傳遞多個(gè)鍵值對(duì)
t1.start()
t2.start()
四.線程結(jié)束
值得思考的是:在上面這份代碼中一共有幾個(gè)線程呢?并非兩個(gè),一共是三個(gè)線程:
注意:主程序會(huì)等待所有子程序結(jié)束之后才會(huì)結(jié)束!
五.相關(guān)函數(shù)介紹
1.threading.Thread() — 創(chuàng)建線程并初始化線程,可以為線程傳遞參數(shù) ;
2.threading.enumerate() — 返回一個(gè)包含正在運(yùn)行的線程的list;
3.threading.activeCount(): 返回正在運(yùn)行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果;
4.Thread.start() — 啟動(dòng)線程 ;
5.Thread.join() — 阻塞函數(shù),一直等到線程結(jié)束為止 ;
6.Thread.isAlive() — 返回線程是否活動(dòng)的;
7.Thread.getName() — 返回線程名;
8.Thread.setName() — 設(shè)置線程名;
9.Thread.setDaemon() — 設(shè)置為后臺(tái)線程,這里默認(rèn)是False,設(shè)置為True之后則主線程不會(huì)再等待子線程結(jié)束才結(jié)束,而是主線程結(jié)束意味程序退出,子線程也立即結(jié)束,注意調(diào)用時(shí)必須設(shè)置在start()之前;
簡單的示例代碼:
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 39 40 41 | # 導(dǎo)入線程threading模塊
importthreading
# 導(dǎo)入內(nèi)置模塊time
importtime
defwash_clothes(*args,**kargcs):
time.sleep(2)
print("wash_clothes:",args)
time.sleep(2)
print("wash_clothes:",kargcs)
defclean_room(*args,**kargcs):
time.sleep(2)
print("clean_room:",args)
time.sleep(2)
print("clean_room:",kargcs)
if__name__=="__main__":
t1=threading.Thread(target=wash_clothes,
args=(1,"猿說python"), # args 傳遞元組,可以同時(shí)傳遞多個(gè)數(shù)據(jù)
kwargs={"a":1,"b":False})# kwargs 傳遞字典,可以同時(shí)傳遞多個(gè)鍵值對(duì)
t2=threading.Thread(target=clean_room,
args=(2,False),# args 傳遞元組,可以同時(shí)傳遞多個(gè)數(shù)據(jù)
kwargs={"c":0.2,"d":False})# kwargs 傳遞字典,可以同時(shí)傳遞多個(gè)鍵值對(duì)
# setDaemon(True)意味著主線程退出,不管子線程執(zhí)行到哪一行,子線程自動(dòng)結(jié)束
# t1.setDaemon(True)
# t2.setDaemon(True)
t1.start()
t2.start()
print("threading.enumerate():",threading.enumerate())
print("threading.activeCount():",threading.activeCount())
print("t1.isAlive():",t1.isAlive())
print("t1.getName():",t1.getName())
print("t2.isAlive():",t2.isAlive())
t2.setName("my_custom_thread_2")
print("t2.getName():",t2.getName())
輸出結(jié)果:
1 2 3 4 5 6 7 8 9 10 | threading.enumerate():[<_MainThread(MainThread,started18388)>,<Thread(Thread-1,started16740)>,<Thread(Thread-2,started17888)>]
threading.activeCount():3
t1.isAlive():True
t1.getName():Thread-1
t2.isAlive():True
t2.getName():my_custom_thread_2
clean_room:(2,False)
wash_clothes:(1,'猿說python')
wash_clothes:{'a':1,'b':False}
clean_room:{'c':0.2,'d':False}
關(guān)于“python線程如何創(chuàng)建和傳參”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
文章標(biāo)題:python線程如何創(chuàng)建和傳參-創(chuàng)新互聯(lián)
新聞來源:http://aaarwkj.com/article20/gpdco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、網(wǎng)站制作、網(wǎng)站維護(hù)、企業(yè)建站、網(wǎng)站收錄、面包屑導(dǎo)航
廣告
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源:
創(chuàng)新互聯(lián)