Python THREADING模組中的JOIN()方法深入理解

來源:互聯網
上載者:User
看了oschina上的兩個代碼,受益匪淺。其中對join()方法不理解,看python官網文檔的介紹:
join([timeout]):等待直到進程結束。這將阻塞正在調用的線程,直到被調用join()方法的線程結束。(好難翻譯,應該是這個意思)

哈哈,這個易懂。
join方法,如果一個線程或者一個函數在執行過程中要調用另外一個線程,並且待到其完成以後才能接著執行,那麼在調用這個線程時可以使用被調用線程的join方法。
複製代碼 代碼如下:


#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
global count, mutex
# 獲得線程名
threadname = threading.currentThread().getName()

for x in xrange(0, int(a)):
# 取得鎖
mutex.acquire()
count = count + 1
# 釋放鎖
mutex.release()
print threadname, x, count
time.sleep(1)

def main(num):
global count, mutex
threads = []

count = 1
# 建立一個鎖
mutex = threading.Lock()
# 先建立線程對象
for x in xrange(0, num):
threads.append(threading.Thread(target=thread_main, args=(10,)))
# 啟動所有線程
for t in threads:
t.start()
# 主線程中等待所有子線程退出
for t in threads:
t.join()

if __name__ == '__main__':
num = 4
# 建立4個線程
main(4)
###################################################################
#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._run_num = num

def run(self):
global count, mutex
threadname = threading.currentThread().getName()

for x in xrange(0, int(self._run_num)):
mutex.acquire()
count = count + 1
mutex.release()
print threadname, x, count
time.sleep(1)

if __name__ == '__main__':
global count, mutex
threads = []
num = 4
count = 1
# 建立鎖
mutex = threading.Lock()
# 建立線程對象
for x in xrange(0, num):
threads.append(Test(10))
# 啟動線程
for t in threads:
t.start()
# 等待子線程結束
for t in threads:
t.join()

在程式中,最後join()方法的調用就明白了,是主進程挨個調用子線程的join()方法。當四個線程都執行完畢後,主線程才會執行下面的代碼,在這裡也就是退出了。
相對應的在網上一起找到的另一個方法:
3.守護進程

setDaemon()

這個方法基本和join是相反的。當我們在程式運行中,執行一個主線程,如果主線程又建立一個子線程,主線程和子線程就分兵兩路,分別運行,那麼當主線程完成想退出時,會檢驗子線程是否完成。如果子線程未完成,則主線程會等待子線程完成後再退出。但是有時候我們需要的是,只要主線程完成了,不管子線程是否完成,都要和主線程一起退出,這時就可以用setDaemon方法啦

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.