推薦使用threading模塊个唧,而不是用thread模塊
thread模塊的方式
主要是三個步驟
1婉称、創(chuàng)建鎖后獲取鎖對象攘乒,添加到鎖列表中
2贤牛、創(chuàng)建線程,并添加上鎖
3则酝、在while循環(huán)中盔夜,直到鎖被釋放掉才進行下一步
#-*- 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(): # 當鎖不在鎖狀態(tài)后跳出循環(huán)
pass
print 'all doneat', ctime()
if __name__ == '__main__':
main()
使用threading模塊的方式
主要三種形式堤魁,主要使用第一種跟第三種
第一種:創(chuàng)建一個 Thread 實例,傳給他一個函數(shù)
1返十、創(chuàng)建 Thread實例妥泉,添加到線程列表
2、啟動線程列表中的線程
3洞坑、通過join阻塞線程直到完成盲链,最后出現(xiàn)結果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
創(chuàng)建一個 Thread 實例,傳給他一個函數(shù)
"""
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: # 創(chuàng)建 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()
第二種:創(chuàng)建一個 Thread 實例,傳一個可調(diào)用的類實例
1刽沾、創(chuàng)建 ThreadFunc 類
2本慕、創(chuàng)建Thread實例,targer調(diào)用類侧漓,傳遞方法锅尘,添加到線程列表
2、啟動線程列表中的線程
3布蔗、通過join阻塞線程直到完成藤违,最后出現(xiàn)結果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
創(chuàng)建一個 Thread 實例,傳一個可調(diào)用的類實例
"""
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: # 創(chuàng)建 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 的子類纵揍,并創(chuàng)建子類的實例
1顿乒、創(chuàng)建 MyThread 類,包含run方法泽谨,繼承threading.Thread
2璧榄、創(chuàng)建Thread實例,通過MyThread來創(chuàng)建吧雹,添加到線程列表
2骨杂、啟動線程列表中的線程
3、通過join阻塞線程直到完成吮炕,最后出現(xiàn)結果
#-*- coding:utf-8 -*-
import threading
from time import sleep, ctime
"""
派生 Thread 的子類腊脱,并創(chuàng)建子類的實例
"""
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: # 創(chuàng)建 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()
對比單線程與多線程去執(zhí)行斐波那契數(shù)列
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()
實戰(zhàn)
獲取亞馬遜的書籍分數(shù)等級
# -*- 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 # 裝飾器龙亲,注冊一個退出函數(shù)陕凹,腳本在退出前就會調(diào)用這個函數(shù)
def _atexit():
print 'all DONE at:', ctime()
if __name__ == '__main__':
main()