理解 Python 中的多线程

1、单线程

import time
import urllib2
 
def get_responses():
    urls = [
        'http://www.google.com',
        'http://www.amazon.com',
        'http://www.ebay.com',
        'http://www.alibaba.com',
        'http://www.reddit.com'
    ]
    start = time.time()
    for url in urls:
        print url
        resp = urllib2.urlopen(url)
        print resp.getcode()
    print "Elapsed time: %s" % (time.time()-start)
 
get_responses()

解释:

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

2、多线程

import urllib2
import time
from threading import Thread
 
class GetUrlThread(Thread):
    def __init__(self, url):
        self.url = url 
        super(GetUrlThread, self).__init__()
 
    def run(self):
        resp = urllib2.urlopen(self.url)
        print self.url, resp.getcode()
 
def get_responses():
    urls = [
        'http://www.google.com', 
        'http://www.amazon.com', 
        'http://www.ebay.com', 
        'http://www.alibaba.com', 
        'http://www.reddit.com'
    ]
    start = time.time()
    threads = []
    for url in urls:
        t = GetUrlThread(url)
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
    print "Elapsed time: %s" % (time.time()-start)
 
get_responses()

解释: 
意识到了程序在执行时间上的提升 
我们写了一个多线程程序来减少cpu的等待时间,当我们在等待一个线程内的网络请求返回时,这时cpu可以切换到其他线程去进行其他线程内的网络请求。 
我们期望一个线程处理一个url,所以实例化线程类的时候我们传了一个url。 
线程运行意味着执行类里的run()方法。 
无论如何我们想每个线程必须执行run()。 
为每个url创建一个线程并且调用start()方法,这告诉了cpu可以执行线程中的run()方法了。 
我们希望所有的线程执行完毕的时候再计算花费的时间,所以调用了join()方法。 
join()可以通知主线程等待这个线程结束后,才可以执行下一条指令。 
每个线程我们都调用了join()方法,所以我们是在所有线程执行完毕后计算的运行时间。 
关于线程: 
cpu可能不会在调用start()后马上执行run()方法。 
你不能确定run()在不同线程建间的执行顺序。 
对于单独的一个线程,可以保证run()方法里的语句是按照顺序执行的。 
这就是因为线程内的url会首先被请求,然后打印出返回的结果。

解决资源竞争

from threading import Lock, Thread
lock = Lock()
some_var = 0
 
class IncrementThread(Thread):
    def run(self):
        #we want to read a global variable
        #and then increment it
        global some_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()
 
def use_increment_thread():
    threads = []
    for i in range(50):
        t = IncrementThread()
        threads.append(t)
        t.start()
    for t in threads:
        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()

解释: 
Lock 用来防止竞争条件 
如果在执行一些操作之前,线程t1获得了锁。其他的线程在t1释放Lock之前,不会执行相同的操作 
我们想要确定的是一旦线程t1已经读取了some_var,直到t1完成了修改some_var,其他的线程才可以读取some_var 
这样读取和修改some_var成了逻辑上的原子操作

加锁保证操作的原子性

from threading import Thread, Lock
import time
 
lock = Lock()
 
class CreateListThread(Thread):
    def run(self):
        self.entries = []
        for i in range(10):
            time.sleep(0.01)
            self.entries.append(i)
        lock.acquire()
        print self.entries
        lock.release()
 
def use_create_list_thread():
    for i in range(3):
        t = CreateListThread()
        t.start()
 
use_create_list_thread()

证明了一个线程不可以修改其他线程内部的变量(非全局变量)。

Python多线程简易版:线程池 threadpool

import threadpool
import time
import urllib2

urls = [
    'http://www.google.com', 
    'http://www.amazon.com', 
    'http://www.ebay.com', 
    'http://www.alibaba.com', 
    'http://www.reddit.com'
]

def myRequest(url):
    resp = urllib2.urlopen(url)
    print url, resp.getcode()


def timeCost(request, n):
  print "Elapsed time: %s" % (time.time()-start)

start = time.time()
pool = threadpool.ThreadPool(5)
reqs = threadpool.makeRequests(myRequest, urls, timeCost)
[ pool.putRequest(req) for req in reqs ]
pool.wait()

makeRequests创建了要开启多线程的函数,以及函数相关参数和回调函数,其中回调函数可以不写,default是无,也就是说makeRequests只需要2个参数就可以运行;

注意:threadpool 是非线程安全的。

 

posted @ 2017-08-04 14:00  zhaojihui  阅读(228)  评论(0编辑  收藏  举报