python 多執行緒中join 的作用

2022-09-29 22:33:19 字數 2458 閱讀 5235

一 前言

溫習python 多程序語法的時候,對 join的理解不是很透徹,本文通過**實踐來加深對 join()的認識。

multiprocessing 是python提供的跨平台版本的多程序模組。multiprocessing可以充分利用多核,提公升程式執行效率。multiprocessing支援子程序,通訊和共享資料,執行不同形式的同步,提供了process、queue、pipe、lock等元件。不過今天重點了解 join。後續文章會逐步學習介紹其他元件或者功能。

二 動手實踐

join()方法可以在當前位置阻塞主程序,帶執行join()的程序結束後再繼續執行主程序的**邏輯。

# encoding: utf-8

"""author: [email protected]

time: 2019/7/30 11:20 am

func:

"""from multiprocessing import process

import os

import time

def now():

return str(time.strftime('%y-%m-%d %h:%m:%s', time.localtime()))

def func_1(name):

print(now() + ' run child process %s (%s)...' % (name, os.getpid()))

time.sleep(4)

print(now() + ' stop child process %s (%s)...\n' % (name, os.getpid()))

def func_程式設計客棧2(name):

print(now() + ' run child process %s (%s)...' % (name, os.getpid()))

time.sleep(8)

print(now() + ' hello world!')

print(now() + ' stop child process %s (%s)...\n' % (name, os.getpid()))

if __name__ == '__main__':

print ('parent process %s.' % os.getpid())

p1 = process(target=func_1, args=('func_1',))

p2 = process(target=func_2, args=('func_2',))

print now() + ' process程式設計客棧 start.'

pywdls1.start()

p2.start()

p1.join()

p2.join()

print now() + ' process end .'

輸出結果

結果顯示

主程序的 process end .是在func1 和func2 結束之後才列印出來的。

2.2 去掉 join() 函式

if __name__ == '__main__':

print ('parent process %s.' % os.getpid())

p1 = process(target=func_1, args=('func_1',))

p2 = process(target=func_2, args=('func_2',))

print now() + ' process start.'

p1.start()

p2.start()

print now() + ' process end .'

結果如下:

2.3 去掉func_2 的 join()

if __name__ == '__main__':

print ('parent process %s.' % os.getpid())

p1 = process(target=func_1, args=('func_1',))

p2 = process(target=func_2, args=('func_2',))

print now() + ' process start.'

p1.start()

p2.start()

p1.join() ### 在p1 執行完之後 。不等待p2 執行,主程序結束。

www.cppcns.comprint now() + ' process end .'

結果如下:

結果顯示主線程 "process end"在func_1 執行結束之後輸出而沒有等待func_2 執行完畢。

2.4 小結

利用多執行緒時,一般都先讓子執行緒呼叫start() ,然後再去呼叫join(),讓主程序等待子程序結束才繼續走後續的邏輯。

思考題能不能每個子程序呼叫start() 之後,然後直接呼叫join() 類似:

p1.start()p1.join()p2.start()p2.join()

Python多執行緒 join

宣告 本文介紹介紹的是thread.threading的 join方法 join timeout none wait until the thread terminates.this blocks the calling thread until the thread whose join meth...

Python多執行緒與多執行緒中join 的用法

文章 python多執行緒與多程序中join 方法的效果是相同的。下面僅以多執行緒為例 首先需要明確幾個概念 知識點一 當乙個程序啟動之後,會預設產生乙個主線程,因為執行緒是程式執行流的最小單元,當設定多執行緒時,主線程會建立多個子執行緒,在python中,預設情況下 其實就是setdaemon f...

Python多執行緒與多執行緒中join 的用法

python多執行緒與多程序中join 方法的效果是相同的。下面僅以多執行緒為例 首先需要明確幾個概念 知識點一 當乙個程序啟動之後,會預設產生乙個主線程,因為執行緒是程式執行流的最小單元,當設定多執行緒時,主線程會建立多個子執行緒,在python中,預設情況下 其實就是setdaemon fals...