Explication détaillée du module threading en python. Threading fournit une API de niveau supérieur à celle du module thread pour fournir la concurrence des threads. Ces threads s'exécutent simultanément et partagent la mémoire.
Regardons l'utilisation spécifique du module threading :
La fonction cible peut instancier un objet Thread, chaque Thread L'objet représente un thread et peut être démarré via la méthode start().
Voici une comparaison entre l'utilisation de la concurrence multi-thread et la non-application de la concurrence multi-thread :
La première est l'opération sans utiliser le multi-threading :
# 🎜🎜 #Le code est le suivant :#!/usr/bin/python #compare for multi threads import time def worker(): print"worker" time.sleep(1) return if__name__ =="__main__": for i in xrange(5): worker()
Le code est le suivant :
#!/usr/bin/python import threading import time defworker(): print"worker" time.sleep(1) return fori in xrange(5): t=threading.Thread(target=worker) t.start()
#!/usr/bin/python #current's number of threads import threading import time defworker(): print"test" time.sleep(1) for i in xrange(5): t=threading.Thread(target=worker) t.start() print"current has %d threads" % (threading.activeCount() -1)
#!/usr/bin/python #test the variable threading.enumerate() import threading import time defworker(): print"test" time.sleep(2) threads=[] for i in xrange(5): t=threading.Thread(target=worker) threads.append(t) t.start() for item in threading.enumerate(): print item print for item in threads: print item
#!/usr/bin/python #create a daemon import threading import time def worker(): time.sleep(3) print"worker" t=threading.Thread(target=worker) t.setDaemon(True) t.start() print"haha"
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!