Python THREADING模块中的JOIN()方法深入理解
Jun 10, 2016 pm 03:17 PM看了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方法啦

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Quels sont les avantages et les inconvénients des modèles ?

Google AI annonce Gemini 1.5 Pro et Gemma 2 pour les développeurs

Pour seulement 250$, le directeur technique de Hugging Face vous apprend étape par étape comment peaufiner Llama 3

Partagez plusieurs frameworks de projets open source .NET liés à l'IA et au LLM

Un guide complet sur le débogage et l'analyse des fonctions Golang

Comment enregistrer la fonction d'évaluation
