多线程编程:
1. 用来加速程序的执行速度(并行);
2.用来模拟生活中随机现象,比如:生产-消费问题,排队-等待问题等等;
下面的一个实例使用的就是: 1. 加速程序的执行速度(并行):
代码语言:javascript复制//1. 这个是一个threading.Thread的派生类, 用来处理多线程函数调用的。使用了装饰者模式
import threading
from time import sleep, ctime
loops = (4,2)
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self) #base class func
self.name = name
self.func = func
self.args = args
# in the other way, use __call__()
# Desiner patter -- Decorator
def run(self):
print 'n starting ', self.name, ' at:',
ctime()
self.res = apply(self.func, self.args)
print self.name, ' nfinished at:',
ctime() , 'n'
def getResult(self):
return self.res
//2. 这里就是调用派生线程类来处理函数,使其并行执行,加速程序的执行
from threading_subclass_project_001 import MyThread
from time import ctime, sleep
def fib(x):
sleep(0.005) #just for test
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))
#list of funcs pointer
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) #call the functions
print funcs[i].__name__, 'finisthed 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 'all Done!'
if __name__ =='__main__':
main()