參考資料地址:https://www.cnblogs.com/fugeny/p/9898971.html#%E5%B9%B6%E8%A1%8C%E8%AE%A1%E7%AE%97
from multiprocessing import Pool
import time
#下面是例子內(nèi)容,我們只需要在此基礎(chǔ)上修改即可
#在這里我們定義自己的函數(shù),也就是說(shuō)輸入是MP3
文件或者是text,然后輸出是MP3文件的長(zhǎng)度
def f(x):
return x*x
#主程序
if __name__ == '__main__':
#這里就是processes=核數(shù)
pool = Pool(processes=4) # start 4 worker processes
#apply_async好處是不會(huì)阻塞進(jìn)程,參數(shù)1就是目標(biāo)函數(shù)名,參數(shù)2是函數(shù)所接受的參數(shù)
result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
#獲取單個(gè)輸出
print result.get(timeout=1) # prints "100" unless your computer is *very* slow
#映射版本的輸出,這個(gè)比較適合多個(gè)采納數(shù)的時(shí)候使用
print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
pool.close()
pool.join()
#迭代器版本
#it = pool.imap(f, range(10))
#print it.next() # prints "0"
#print it.next() # prints "1"
#print it.next(timeout=1) # prints "4" unless your computer is *very* slow
result = pool.apply_async(time.sleep, (10,))
print result.get(timeout=1) # raises multiprocessing.TimeoutError
如果結(jié)果不正常,我們需要ctrl+c終止程序
參考資料2地址:https://www.cnblogs.com/zz27zz/p/7886146.html
import time
import threadpool
#定義執(zhí)行函數(shù)
def sayhello(str):
print "Hello ",str
time.sleep(2)
#執(zhí)行函數(shù)輸入的參數(shù)列表
name_list =['xiaozi','aa','bb','cc']
#測(cè)試時(shí)間的time模塊可以去除
start_time = time.time()
pool = threadpool.ThreadPool(10) #此處的10是poolsize 一般也就是cpu數(shù)量
requests = threadpool.makeRequests(sayhello, name_list) #導(dǎo)入函數(shù)和函數(shù)參數(shù)
[pool.putRequest(req) for req in requests]
pool.wait()
print '%d second'% (time.time()-start_time)