推荐使用threading模块,而不是用thread模块
thread模块的方式
主要是三个步骤
1、创建锁后获取锁对象,添加到锁列表中
2、创建线程,并添加上锁
3、在while循环中,直到锁被释放掉才进行下一步
#-*- coding:utf-8 -*-
import thread
from time import sleep, ctime
loops = [4,2]
def loop(nloop, nsec, lock):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
lock.release() # 释放锁
def main():
print 'start at: ', ctime()
locks = []
nloops = range(len(loops))
for i in nloops:
lock = thread.allocate_lock() # 获得锁对象
lock.acquire() # 取得锁,并把锁锁上
locks.append(lock) # 添加锁到 locks 列表
for i in nloops:
thread.start_new_thread(loop, (i, loops[i], locks[i]))
for i in nloops:
while locks[i].locked(): # 当锁不在锁状态后跳出循环
pass
print 'all doneat', ctime()
if __name__ == '__main__':
main()
使用threading模块的方式
主要三种形式,主要使用第一种跟第三种
第一种:创建一个 Thread 实例,传给他一个函数
1、创建 Thread实例,添加到线程列表
2、启动线程列表中的线程
3、通过join阻塞线程直到完成,最后出现结果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
创建一个 Thread 实例,传给他一个函数
"""
loops = [ 4, 2]
def loop(nloop, nsec):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
print 'start at: ', ctime()
threads = []
nloops = range(len(loops))
for i in nloops: # 创建 Thread 实例
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t)
for i in nloops: # start threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # thread to finish
print 'all doneat', ctime()
if __name__ == '__main__':
main()
第二种:创建一个 Thread 实例,传一个可调用的类实例
1、创建 ThreadFunc 类
2、创建Thread实例,targer调用类,传递方法,添加到线程列表
2、启动线程列表中的线程
3、通过join阻塞线程直到完成,最后出现结果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
创建一个 Thread 实例,传一个可调用的类实例
"""
loops = [ 4, 2]
class ThreadFunc(object):
def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args
def __call__(self):
self.func(*self.args)
def loop(nloop, nsec):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
print 'start at: ', ctime()
threads = []
nloops = range(len(loops))
for i in nloops: # 创建 Thread 实例
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t)
for i in nloops: # start threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # thread to finish
print 'all doneat', ctime()
if __name__ == '__main__':
main()
第三种:派生 Thread 的子类,并创建子类的实例
1、创建 MyThread 类,包含run方法,继承threading.Thread
2、创建Thread实例,通过MyThread来创建,添加到线程列表
2、启动线程列表中的线程
3、通过join阻塞线程直到完成,最后出现结果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
派生 Thread 的子类,并创建子类的实例
"""
loops = (4, 2)
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
def run(self):
self.func(*self.args)
def loop(nloop, nsec):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
def main():
print 'start at: ', ctime()
threads = []
nloops = range(len(loops))
for i in nloops: # 创建 Thread 实例
t = MyThread(loop, (i, loops[i]), loop.__name__)
threads.append(t)
for i in nloops: # start threads
threads[i].start()
for i in nloops: # wait for all
threads[i].join() # thread to finish
print 'all doneat', ctime()
if __name__ == '__main__':
main()
最后独立出来MyThread类
import threading
from time import ctime
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.args = args
self.func = func
def getResult(self):
return self.res
def run(self):
print 'staring', self.name, 'at:', ctime()
self.res = self.func(*self.args)
print self.name, 'finished at:', ctime()
对比单线程与多线程去执行斐波那契数列
from myThread import MyThread
from time import ctime, sleep
def fib(x):
sleep(0.005)
if x < 2:return 1
return (fib(x-2)+fib(x-1))
def fac(x):
sleep(0.1)
if x < 2: return 1
return (x * fac(x-1))
def sum(x):
sleep(0.1)
if x < 2:return 1
return (x + sum(x-1))
funcs = [fib, fac, sum]
n = 12
def main():
nfuncs = range(len(funcs))
print '*** SINGLE THREAD'
for i in nfuncs:
print 'starting', funcs[i].__name__, 'at:', ctime
print funcs[i](n)
print funcs[i].__name__, 'finished at:', ctime()
print '\n *** MULTIPLE THREADS'
threads = []
for i in nfuncs:
t = MyThread(funcs[i], (n, ), funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
print threads[i].getResult()
print 'all DONE'
if __name__ == '__main__':
main()
实战
获取亚马逊的书籍分数等级
# -*- coding:utf-8 -*-
from atexit import register
from re import compile
from threading import Thread
from time import ctime
from urllib2 import urlopen as uopen
REGEX = compile('#([\d,]+) in Books ')
AMZN = 'http://amazon.com/dp/'
ISBNs = {
'0132269937' : 'Core Python Programming',
'0132356139' : 'Python Web Development with Django',
'0137143419' : 'Python Fundamentals',
}
def getRanking(isbn):
page = uopen('%s%s' % (AMZN, isbn)) # or str.format()
data = page.read() #page得到服务器返回的对象,read()下载整个文件
page.close() # 关闭这个文件
return REGEX.findall(data)[0] # 匹配到的值
def _showRanking(isbn):
Thread(target=_showRanking, args=(isbn,)).start
print '- %r ranked %s' % (ISBNs[isbn], getRanking(isbn))
def main():
print 'At', ctime(), 'on Amazon...'
for isbn in ISBNs:
_showRanking(isbn)
@register # 装饰器,注册一个退出函数,脚本在退出前就会调用这个函数
def _atexit():
print 'all DONE at:', ctime()
if __name__ == '__main__':
main()