我想要实现的目标是产生多个父母,每个父母都做一些工作,然后产生几个孩子来检查其他事情,并在父母身上获取这些结果以做进一步的工作。我还试图制作 2 个不同的产卵限制,因为父母的工作可以比孩子做的更多。
我将如何做到这一点?
如果我不使用limit2,它会起作用,但我想拥有两个限制器。
import trio
import asks
import time
import random
async def child(parent, i, sender, limit2):
async with limit2:
print('Parent {0}, Child {1}: started! Sleeping now...'.format(parent, i))
#await trio.sleep(random.randrange(0, 3))
print('Parent {0}, Child {1}: exiting!'.format(parent, i))
async with sender:
await sender.send('Parent {0}, Child {1}: exiting!'.format(parent, i))
async def parent(i, limit):
async with limit:
print('Parent {0}: started! Sleeping now...'.format(i))
#await trio.sleep(random.randrange(0, 3))
sender, receiver = trio.open_memory_channel(10)
limit2 = trio.CapacityLimiter(2)
async with trio.open_nursery() as nursery:
for j in range(10):
nursery.start_soon(child, i, j, sender, limit2)
async with receiver:
async for value in receiver:
print('Got value: {!r}'.format(value))
print('Parent {0}: exiting!'.format(i))
async def main():
limit = trio.CapacityLimiter(1)
async with trio.open_nursery() as nursery:
for i in range(1):
nursery.start_soon(parent, i, limit)
if __name__ == "__main__":
start_time = time.perf_counter()
trio.run(main)
duration = time.perf_counter() - start_time
print("Took {:.2f} seconds".format(duration))