Maison développement back-end Tutoriel Python 深入理解 Python 中的多线程 新手必看

深入理解 Python 中的多线程 新手必看

Dec 14, 2016 pm 05:52 PM

示例1
我们将要请求五个不同的url:
单线程

import time
import urllib2
   
defget_responses():
  urls=[
    ‘http://www.baidu.com',
    ‘http://www.amazon.com',
    ‘http://www.ebay.com',
    ‘http://www.alibaba.com',
    ‘http://www.jb51.net'
  ]
  start=time.time()
  forurlinurls:
    printurl
    resp=urllib2.urlopen(url)
    printresp.getcode()
  print”Elapsed time: %s”%(time.time()-start)
   
get_responses()
Copier après la connexion

输出是:
http://www.baidu.com200
http://www.amazon.com200
http://www.ebay.com200
http://www.alibaba.com200
http://www.jb51.net200
Elapsed time:3.0814409256

解释:
url顺序的被请求
除非cpu从一个url获得了回应,否则不会去请求下一个url
网络请求会花费较长的时间,所以cpu在等待网络请求的返回时间内一直处于闲置状态。
多线程

import urllib2
import time
from threading import Thread
   
classGetUrlThread(Thread):
  def__init__(self, url):
    self.url=url
    super(GetUrlThread,self).__init__()
   
  defrun(self):
    resp=urllib2.urlopen(self.url)
    printself.url, resp.getcode()
   
defget_responses():
  urls=[
    ‘http://www.baidu.com',
    ‘http://www.amazon.com',
    ‘http://www.ebay.com',
    ‘http://www.alibaba.com',
    ‘http://www.jb51.net'
  ]
  start=time.time()
  threads=[]
  forurlinurls:
    t=GetUrlThread(url)
    threads.append(t)
    t.start()
  fortinthreads:
    t.join()
  print”Elapsed time: %s”%(time.time()-start)
   
get_responses()
Copier après la connexion

输出:
http://www.jb51.net200
http://www.baidu.com200
http://www.amazon.com200
http://www.alibaba.com200
http://www.ebay.com200
Elapsed time:0.689890861511

解释:

意识到了程序在执行时间上的提升
我们写了一个多线程程序来减少cpu的等待时间,当我们在等待一个线程内的网络请求返回时,这时cpu可以切换到其他线程去进行其他线程内的网络请求。
我们期望一个线程处理一个url,所以实例化线程类的时候我们传了一个url。
线程运行意味着执行类里的run()方法。
无论如何我们想每个线程必须执行run()。
为每个url创建一个线程并且调用start()方法,这告诉了cpu可以执行线程中的run()方法了。
我们希望所有的线程执行完毕的时候再计算花费的时间,所以调用了join()方法。
join()可以通知主线程等待这个线程结束后,才可以执行下一条指令。
每个线程我们都调用了join()方法,所以我们是在所有线程执行完毕后计算的运行时间。

关于线程:

cpu可能不会在调用start()后马上执行run()方法。
你不能确定run()在不同线程建间的执行顺序。
对于单独的一个线程,可以保证run()方法里的语句是按照顺序执行的。
这就是因为线程内的url会首先被请求,然后打印出返回的结果。

实例2

我们将会用一个程序演示一下多线程间的资源竞争,并修复这个问题。

from threading import Thread
   
#define a global variable
some_var=0
   
classIncrementThread(Thread):
  defrun(self):
    #we want to read a global variable
    #and then increment it
    globalsome_var
    read_value=some_var
    print”some_var in %s is %d”%(self.name, read_value)
    some_var=read_value+1
    print”some_var in %s after increment is %d”%(self.name, some_var)
   
defuse_increment_thread():
  threads=[]
  foriinrange(50):
    t=IncrementThread()
    threads.append(t)
    t.start()
  fortinthreads:
    t.join()
  print”After 50 modifications, some_var should have become 50″
  print”After 50 modifications, some_var is %d”%(some_var,)
   
use_increment_thread()
Copier après la connexion

多次运行这个程序,你会看到多种不同的结果。
解释:
有一个全局变量,所有的线程都想修改它。
所有的线程应该在这个全局变量上加 1 。
有50个线程,最后这个数值应该变成50,但是它却没有。
为什么没有达到50?
在some_var是15的时候,线程t1读取了some_var,这个时刻cpu将控制权给了另一个线程t2。
t2线程读到的some_var也是15
t1和t2都把some_var加到16
当时我们期望的是t1 t2两个线程使some_var + 2变成17
在这里就有了资源竞争。
相同的情况也可能发生在其它的线程间,所以出现了最后的结果小于50的情况。
解决资源竞争

from threading import Lock, Thread
lock=Lock()
some_var=0
   
classIncrementThread(Thread):
  defrun(self):
    #we want to read a global variable
    #and then increment it
    globalsome_var
    lock.acquire()
    read_value=some_var
    print”some_var in %s is %d”%(self.name, read_value)
    some_var=read_value+1
    print”some_var in %s after increment is %d”%(self.name, some_var)
    lock.release()
   
defuse_increment_thread():
  threads=[]
  foriinrange(50):
    t=IncrementThread()
    threads.append(t)
    t.start()
  fortinthreads:
    t.join()
  print”After 50 modifications, some_var should have become 50″
  print”After 50 modifications, some_var is %d”%(some_var,)
   
use_increment_thread()
Copier après la connexion

再次运行这个程序,达到了我们预期的结果。
解释:
Lock 用来防止竞争条件
如果在执行一些操作之前,线程t1获得了锁。其他的线程在t1释放Lock之前,不会执行相同的操作
我们想要确定的是一旦线程t1已经读取了some_var,直到t1完成了修改some_var,其他的线程才可以读取some_var
这样读取和修改some_var成了逻辑上的原子操作。
实例3
让我们用一个例子来证明一个线程不能影响其他线程内的变量(非全局变量)。
time.sleep()可以使一个线程挂起,强制线程切换发生。

from threading import Thread
import time
   
classCreateListThread(Thread):
  defrun(self):
    self.entries=[]
    foriinrange(10):
      time.sleep(1)
      self.entries.append(i)
    printself.entries
   
defuse_create_list_thread():
  foriinrange(3):
    t=CreateListThread()
    t.start()
   
use_create_list_thread()
Copier après la connexion

运行几次后发现并没有打印出争取的结果。当一个线程正在打印的时候,cpu切换到了另一个线程,所以产生了不正确的结果。我们需要确保print self.entries是个逻辑上的原子操作,以防打印时被其他线程打断。
我们使用了Lock(),来看下边的例子。

from threading import Thread, Lock
import time
   
lock=Lock()
   
classCreateListThread(Thread):
  defrun(self):
    self.entries=[]
    foriinrange(10):
      time.sleep(1)
      self.entries.append(i)
    lock.acquire()
    printself.entries
    lock.release()
   
defuse_create_list_thread():
  foriinrange(3):
    t=CreateListThread()
    t.start()
   
use_create_list_thread()
Copier après la connexion

  这次我们看到了正确的结果。证明了一个线程不可以修改其他线程内部的变量(非全局变量)。

以上就是 Python 中的多线程,更多相关文章请关注PHP中文网(www.php.cn)!


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Tags d'article chaud

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

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

Comment utiliser Python pour trouver la distribution ZIPF d'un fichier texte Comment utiliser Python pour trouver la distribution ZIPF d'un fichier texte Mar 05, 2025 am 09:58 AM

Comment utiliser Python pour trouver la distribution ZIPF d'un fichier texte

Comment utiliser la belle soupe pour analyser HTML? Comment utiliser la belle soupe pour analyser HTML? Mar 10, 2025 pm 06:54 PM

Comment utiliser la belle soupe pour analyser HTML?

Filtrage d'image en python Filtrage d'image en python Mar 03, 2025 am 09:44 AM

Filtrage d'image en python

Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch? Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch? Mar 10, 2025 pm 06:52 PM

Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch?

Modules mathématiques en python: statistiques Modules mathématiques en python: statistiques Mar 09, 2025 am 11:40 AM

Modules mathématiques en python: statistiques

Introduction à la programmation parallèle et simultanée dans Python Introduction à la programmation parallèle et simultanée dans Python Mar 03, 2025 am 10:32 AM

Introduction à la programmation parallèle et simultanée dans Python

Sérialisation et désérialisation des objets Python: partie 1 Sérialisation et désérialisation des objets Python: partie 1 Mar 08, 2025 am 09:39 AM

Sérialisation et désérialisation des objets Python: partie 1

Comment implémenter votre propre structure de données dans Python Comment implémenter votre propre structure de données dans Python Mar 03, 2025 am 09:28 AM

Comment implémenter votre propre structure de données dans Python

See all articles