我正在尝试使用multiprocessing.Pool的map_async。在这个最小的例子中。我应该增加一个classe属性,并且应该增加回调函数中的计数器。但是,似乎永远不会调用回调函数。
import random
from time import time
from multiprocessing import Pool
class BuyerAgent:
def __init__(self):
self.i = 0
class ZITraders:
def __init__(self):
self.max_number_of_trades = 5000
self.buyers = [BuyerAgent()
for _ in xrange(5000)]
def do_trading(self):
counter = 0
dd = 0
def cb(datuum):
dd = datuum
counter += 1
print 'cb'
po = Pool()
po.map_async(match, reverb(self.buyers, self.buyers, self.max_number_of_trades), callback=cb)
po.close()
po.join()
print counter, dd
def reverb(buyers, sellers, num):
for n in xrange(num):
yield random.choice(buyers), random.choice(sellers)
def match(buyer, seller):
print 'match'
buyer.i += 1
return buyer.i
if __name__ == '__main__':
t = time()
simulation = ZITraders()
simulation.do_trading()
print('time %2.2f' % (time() - t))
结果:
MacBook-Pro:zi taghawi$ python zitraders.py
0 0
time 0.13