python 在threading中如何處理主進(jìn)程和子線程的關(guān)系
之前用python的多線程,總是處理不好進(jìn)程和線程之間的關(guān)系。后來(lái)發(fā)現(xiàn)了join和setDaemon函數(shù),才終于弄明白。下面總結(jié)一下。
1.使用join函數(shù)后,主進(jìn)程會(huì)在調(diào)用join的地方等待子線程結(jié)束,然后才接著往下執(zhí)行。
join使用實(shí)例如下:
import time import random import threading class worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): t = random.randint(1,10) time.sleep(t) print "This is " + self.getName() + ";I sleep %d second."%(t) tsk = [] for i in xrange(0,5): time.sleep(0.1) thread = worker() thread.start() tsk.append(thread) for tt in tsk: tt.join() print "This is the end of main thread."
運(yùn)行結(jié)果如下:
# python testjoin.py This is Thread-3;I sleep 2 second. This is Thread-1;I sleep 4 second. This is Thread-2;I sleep 7 second. This is Thread-4;I sleep 7 second. This is Thread-5;I sleep 7 second. This is the end of main thread.
這里創(chuàng)建了5個(gè)子線程,每個(gè)線程隨機(jī)等待1-10秒后打印退出;主線程分別等待5個(gè)子線程結(jié)束。最后結(jié)果是先顯示各個(gè)子線程,再顯示主進(jìn)程的結(jié)果。
2. 如果使用的setDaemon函數(shù),則與join相反,主進(jìn)程結(jié)束的時(shí)候不會(huì)等待子線程。
setDaemon函數(shù)使用實(shí)例:
import time import random import threading class worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): t = random.randint(1,10) time.sleep(t) print "This is " + self.getName() + ";I sleep %d second."%(t) tsk = [] for i in xrange(0,5): time.sleep(0.1) thread = worker() thread.setDaemon(True) thread.start() tsk.append(thread) print "This is the end of main thread."
這里設(shè)置主進(jìn)程為守護(hù)進(jìn)程,當(dāng)主進(jìn)程結(jié)束的時(shí)候,子線程被中止
運(yùn)行結(jié)果如下:
#python testsetDaemon.py
This is the end of main thread.
3、如果沒(méi)有使用join和setDaemon函數(shù),則主進(jìn)程在創(chuàng)建子線程后,直接運(yùn)行后面的代碼,主程序一直掛起,直到子線程結(jié)束才能結(jié)束。
import time import random import threading class worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): t = random.randint(1,10) time.sleep(t) print "This is " + self.getName() + ";I sleep %d second."%(t) tsk = [] for i in xrange(0,5): time.sleep(0.1) thread = worker() thread.start() tsk.append(thread) print "This is the end of main thread."
運(yùn)行結(jié)果如下:
# python testthread.py This is the end of main thread. This is Thread-4;I sleep 1 second. This is Thread-3;I sleep 7 second. This is Thread-5;I sleep 7 second. This is Thread-1;I sleep 10 second. This is Thread-2;I sleep 10 second.
補(bǔ)充知識(shí):Python Thread和Process對(duì)比
原因:進(jìn)程和線程的差距(方向不同,之針對(duì)這個(gè)實(shí)例)
# coding=utf-8 import logging import multiprocessing import os import time from threading import Thread logging.basicConfig( level=logging.INFO, format="%(asctime)s 【 %(process)d 】 %(processName)s %(message)s" ) def func (i): # logging.info(f'子:{os.getpid()},\t{i}') return f'子:{os.getpid()},\t{i}' def main (ctx): start01 = time.time() ts = [Thread(target=func, args=(i,)) for i in range(100)] [t.start() for t in ts] [t.join() for t in ts] end01 = time.time() - start01 logging.info(f"線程花費(fèi)的時(shí)間:{end01}秒") start02 = time.time() ps = [ctx.Process(target=func, args=(i,)) for i in range(100)] [p.start() for p in ps] [p.join() for p in ps] end02 = time.time() - start02 logging.info(f"進(jìn)程花費(fèi)的時(shí)間:{end02}秒") if __name__ == '__main__': # windows 啟動(dòng)方式 multiprocessing.set_start_method('spawn') # 獲取上下文 ctx = multiprocessing.get_context('spawn') # 檢查這是否是凍結(jié)的可執(zhí)行文件中的偽分支進(jìn)程。 ctx.freeze_support() main(ctx)
輸出:
2019-10-06 14:17:22,729 【 7412 】 MainProcess 線程花費(fèi)的時(shí)間:0.012967586517333984秒
2019-10-06 14:17:25,671 【 7412 】 MainProcess 進(jìn)程花費(fèi)的時(shí)間:2.9418249130249023秒
以上這篇python 在threading中如何處理主進(jìn)程和子線程的關(guān)系就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python批量實(shí)現(xiàn)Word/EXCEL/PPT轉(zhuǎn)PDF
在日常辦公和文檔處理中,有時(shí)我們需要將多個(gè)Word文檔、Excel表格或PPT演示文稿轉(zhuǎn)換為PDF文件,本文將介紹如何使用Python編程語(yǔ)言批量實(shí)現(xiàn)將多個(gè)Word、Excel和PPT文件轉(zhuǎn)換為PDF文件,需要的可以參考下2023-09-09Python實(shí)現(xiàn)基于Fasttext的商品評(píng)論數(shù)據(jù)分類(lèi)的操作流程
這篇文章主要介紹了Python實(shí)現(xiàn)基于Fasttext的商品評(píng)論數(shù)據(jù)分類(lèi),今天使用的fasttext更像是一個(gè)集成的庫(kù),把向量化和分類(lèi)一起做掉了,這個(gè)對(duì)于使用層面來(lái)講就更方便了一些,需要的朋友可以參考下2022-06-06Flask運(yùn)用Xterm實(shí)現(xiàn)交互終端的示例詳解
Xterm是一個(gè)基于X Window System的終端仿真器(Terminal Emulator),Xterm最初由MIT開(kāi)發(fā),它允許用戶在X Window環(huán)境下運(yùn)行文本終端程序,本文給大家介紹了Flask運(yùn)用Xterm實(shí)現(xiàn)交互終端的示例詳解,文中有詳細(xì)的代碼講解,需要的朋友可以參考下2023-11-11python基于隱馬爾可夫模型實(shí)現(xiàn)中文拼音輸入
這篇文章主要介紹了python基于隱馬爾可夫模型實(shí)現(xiàn)中文拼音輸入的相關(guān)資料,需要的朋友可以參考下2016-04-04python圖片剪裁代碼(圖片按四個(gè)點(diǎn)坐標(biāo)剪裁)
這篇文章主要介紹了python圖片剪裁代碼(圖片按四個(gè)點(diǎn)坐標(biāo)剪裁),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03基于Python實(shí)現(xiàn)一個(gè)自動(dòng)關(guān)機(jī)程序并打包成exe文件
這篇文章主要介紹了通過(guò)Python創(chuàng)建一個(gè)可以自動(dòng)關(guān)機(jī)的小程序,并打包成exe文件。文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的同學(xué)可以了解一下2021-12-12