1.對單個元素的函數使用線程池:
# encoding:utf-8 __author__='xijun.gong' import threadpool def func(name): print 'hi {}\n'.format(name) if __name__ == '__main__': data = ['xijun.gong', 'xijun', 'gxjun'] pool = threadpool.ThreadPool(5) reqs = threadpool.makeRequests(func, data) [pool.putRequest(req) for req in reqs] pool.wait()
結果:
hi xijun.gong
hi xijun
hi gxjun
2.對於多個參數的情況使用方式:
# encoding:utf-8 __author__='xijun.gong' import threadpool def func(name): print 'hi {}\n'.format(name) def add(a,b): print '{0}+{1}={2}'.format(a,b,(a+b)) if __name__ == '__main__': data = [((index,i),None) for index,i in enumerate(range(1,10,2))]#(index,i)也可以寫成[index,i] pool = threadpool.ThreadPool(5) reqs = threadpool.makeRequests(add, data) [pool.putRequest(req) for req in reqs] pool.wait()
結果:
0+1=1
1+3=4
3+7=10
2+5=7
4+9=13
3.如果我們想不安參數順序賦值,可以使用這種方式:
# encoding:utf-8 __author__='xijun.gong' import threadpool def func(name): print 'hi {}\n'.format(name) def add(a,b): print '{0}+{1}={2}'.format(a,b,(a+b)) if __name__ == '__main__': data = [(None,{'b':index,'a':i}) for index,i in enumerate(range(1,10,2))] pool = threadpool.ThreadPool(5) reqs = threadpool.makeRequests(add, data) [pool.putRequest(req) for req in reqs] pool.wait()
結果:
1+0=1
3+1=4
5+2=7
7+3=10
9+4=13