Python 多线程 鸡肋也很好吃

Python 多线程

“Python解释器使用了内部的GIL(Global Interpreter Lock,全局解释器锁定),在任意指定的时刻只允许单个Python线程的执行,即便存在多个可用的处理器。在计算密集型程序中,这严重限制了线程的作用——事实上,在计算密集型程序中使用线程,经常比仅仅按照顺序执行同样的工作慢得多。因此,实际上应该只在主要关注I/O的程序,如网络服务器中使用线程。对于计算密集程度更高的任务,最好使用C扩展模块或multiprocessing模块来代替。”

Python的多线程被很多人认为是鸡肋,上面这段摘自《Python 参考手册》很好的说明了个中原因。但是本着“存在即合理的”的原则,我还是找到了一个多线程的应用。

参考了stackoverflow上的一个例子。

Proper use of threads in Python is invariably connected to I/O operations (since CPython doesn’t use multiple cores to run CPU-bound tasks anyway, the only reason for threading is not blocking the process while there’s a wait for some I/O).

代码1:使用线程

import threading
import urllib2
import time

# called by each thread
def get_url(url):
    content = urllib2.urlopen(url).read()

theurls = ["http://www.qq.com", "http://www.baidu.com"]


start_time = time.time()
for u in theurls:
    t = threading.Thread(target=get_url, args = (u))
    t.daemon = True
    t.start()

end_time = time.time()

print end_time - start_time

代码2:不使用线程

import urllib2
import time


def get_url(url):
    content = urllib2.urlopen(url).read()

theurls = ["http://www.qq.com", "http://www.baidu.com"]

start_time = time.time()
for u in theurls:
    get_url(u)
end_time = time.time()

print end_time - start_time

多运行几次,尽量消除网络不稳定造成误差,可以大概看出两者的时间差距还是很大的。
在本机测试中,多线程的时间在0.001秒左右,普通的循环在0.1秒左右。

你可能感兴趣的:(python)