python多線程怎么使用

最近用到了多線程的調(diào)用,看前輩們的自動(dòng)化用例實(shí)在是看不懂辟拷。所以網(wǎng)上搜了些資料學(xué)習(xí)缴阎,整理如下蝙斜。

首先,需要知道要import哪些包

python2有3個(gè)可用:

????????????????import thread

????????????????import threading

????????????????import multiprocessing(進(jìn)程)

python3新增了一個(gè)concurrent.futures泌绣,也是超好用的

其次钮追,舉個(gè)小例子演示怎么使用

場(chǎng)景:有個(gè)打印當(dāng)前時(shí)間的函數(shù)print_time,想要并發(fā)執(zhí)行,

1阿迈、import thread

調(diào)用方式:thread.start_new_thread(print_time, ("Thread-1", 2,))元媚,拷貝下方代碼,可以直接運(yùn)行

#-*- coding: utf-8 -*-

import thread

import time

# 為線程定義一個(gè)函數(shù)

def print_time(threadName, delay):

count =0

? ? while count <5:

time.sleep(delay)

count +=1

? ? ? ? print "%s: %s" % (threadName, time.ctime(time.time()))

if __name__ =='__main__':

# 創(chuàng)建兩個(gè)線程-----------使用thread

? ? try:

thread.start_new_thread(print_time, ("Thread-1", 2,))

thread.start_new_thread(print_time, ("Thread-2", 4,))

except:

print "Error: unable to start thread"

? ? while 1:

pass

2苗沧、import threading

調(diào)用方法1:直接使用threading.Thread調(diào)用刊棕;方法2:改寫threading.Thread的執(zhí)行方法

方法1:

#-*- coding: utf-8 -*-

# import thread

import time

import threading

exitFlag =0

def print_time(threadName, delay):

count =0

? ? while count <5:

if exitFlag:

(threading.thread).exit()

time.sleep(delay)

count +=1

? ? ? ? print "%s: %s" % (threadName, time.ctime(time.time()))

if __name__ =='__main__':

threads = []

thread1 = threading.Thread(target=print_time,args = ("thread-1",2))

thread2 = threading.Thread(target=print_time, args=("thread-2", 2))

threads.append(thread1)

threads.append(thread2)

for threadin threads:

thread.start()

for threadin threads:

thread.join()

方法2:

#-*- coding: utf-8 -*-

# import thread

import time

import threading

exitFlag =0

class myThread(threading.Thread):

def __init__(self,threadID,name,delay):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.delay = delay

def run(self):#把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會(huì)直接運(yùn)行run函數(shù)

? ? ? ? print "Starting "+self.name

print_time(self.name,self.delay)

print "Exiting "+self.name

def print_time(threadName, delay):

count =0

? ? while count <5:

if exitFlag:

# threading.thread.exit()

? ? ? ? ? ? (threading.thread).exit()

time.sleep(delay)

count +=1

? ? ? ? print "%s: %s" % (threadName, time.ctime(time.time()))

if __name__ =='__main__':

# 使用threading.thread------------------

? ? thread1 = myThread(1,"thread-1",1)

thread2 = myThread(2,"thread-2",2)

thread1.start()

thread2.start()

3、import?multiprocessing

#-*- coding: utf-8 -*-

import time

import multiprocessing

exitFlag =0

def print_time(threadName, delay):

count =0

? ? while count <5:

if exitFlag:

# threading.thread.exit()

? ? ? ? ? ? (threading.thread).exit()

time.sleep(delay)

count +=1

? ? ? ? print "%s: %s" % (threadName, time.ctime(time.time()))

if __name__ =='__main__':

# 使用multiprocessing---------------

? ? threads = []

thread1 = multiprocessing.Process(target=print_time,args = ("thread-1",2))

thread2 = multiprocessing.Process(target=print_time, args=("thread-2", 2))

threads.append(thread1)

threads.append(thread2)

for threadin threads:

thread.start()

for threadin threads:

thread.join()

總結(jié)

進(jìn)程和線程怎么選取待逞,菜鳥教程上有個(gè)帖子寫的特別好:CPU密集型選擇多進(jìn)程甥角;IO密集型選擇多線程。原文如下:

資料顯示识樱,如果多線程的進(jìn)程是CPU密集型的嗤无,那多線程并不能有多少效率上的提升,相反還可能會(huì)因?yàn)榫€程的頻繁切換怜庸,導(dǎo)致效率下降当犯,推薦使用多進(jìn)程;如果是IO密集型割疾,多線程進(jìn)程可以利用IO阻塞等待時(shí)的空閑時(shí)間執(zhí)行其他線程嚎卫,提升效率。(引自:https://www.runoob.com/w3cnote/python-single-thread-multi-thread-and-multi-process.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末宏榕,一起剝皮案震驚了整個(gè)濱河市拓诸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌担扑,老刑警劉巖恰响,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異涌献,居然都是意外死亡胚宦,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枢劝,“玉大人井联,你說我怎么就攤上這事∧裕” “怎么了烙常?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)鹤盒。 經(jīng)常有香客問我蚕脏,道長(zhǎng),這世上最難降的妖魔是什么侦锯? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任驼鞭,我火速辦了婚禮,結(jié)果婚禮上尺碰,老公的妹妹穿的比我還像新娘挣棕。我一直安慰自己,他們只是感情好亲桥,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布洛心。 她就那樣靜靜地躺著,像睡著了一般题篷。 火紅的嫁衣襯著肌膚如雪词身。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天悼凑,我揣著相機(jī)與錄音偿枕,去河邊找鬼。 笑死户辫,一個(gè)胖子當(dāng)著我的面吹牛渐夸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播渔欢,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼墓塌,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了奥额?” 一聲冷哼從身側(cè)響起苫幢,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎垫挨,沒想到半個(gè)月后韩肝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡九榔,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年哀峻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了涡相。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡剩蟀,死狀恐怖催蝗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情育特,我是刑警寧澤丙号,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站缰冤,受9級(jí)特大地震影響犬缨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锋谐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一遍尺、第九天 我趴在偏房一處隱蔽的房頂上張望截酷。 院中可真熱鬧涮拗,春花似錦、人聲如沸迂苛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)三幻。三九已至就漾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間念搬,已是汗流浹背抑堡。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留朗徊,地道東北人首妖。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像爷恳,于是被迫代替她去往敵國(guó)和親有缆。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354