python asyncio future_Python中的asyncio模块中的Future和Task的区别?

Future是用来接受异步的结果的。

Task是将future和协程对象组合到一起,用于事件循环的。

我的电脑上跑更改后和更改前的效果是不一样的。顺序相反。相反的原因在于set(coros_or_futures),是不能保证维持list的原有顺序。

你之所以跑出来是一样的,是因为gather函数里是这样

def gather(*coros_or_futures, loop=None, return_exceptions=False):

"""Return a future aggregating results from the given coroutines

or futures.

All futures must share the same event loop. If all the tasks are

done successfully, the returned future's result is the list of

results (in the order of the original sequence, not necessarily

the order of results arrival). If *return_exceptions* is True,

exceptions in the tasks are treated the same as successful

results, and gathered in the result list; otherwise, the first

raised exception will be immediately propagated to the returned

future.

Cancellation: if the outer Future is cancelled, all children (that

have not completed yet) are also cancelled. If any child is

cancelled, this is treated as if it raised CancelledError --

the outer Future is *not* cancelled in this case. (This is to

prevent the cancellation of one child to cause other children to

be cancelled.)

"""

if not coros_or_futures:

if loop is None:

loop = events.get_event_loop()

outer = loop.create_future()

outer.set_result([])

return outer

arg_to_fut = {}

for arg in set(coros_or_futures):

print('--------------------', arg)

if not isinstance(arg, futures.Future):

print('-----------不是一个future-------,就会自动执行ensure_future')

fut = ensure_future(arg, loop=loop)

if loop is None:

loop = fut._loop

# The caller cannot control this future, the "destroy pending task"

# warning should not be emitted.

fut._log_destroy_pending = False

else:

fut = arg

if loop is None:

loop = fut._loop

elif fut._loop is not loop:

raise ValueError("futures are tied to different event loops")

arg_to_fut[arg] = fut

children = [arg_to_fut[arg] for arg in coros_or_futures]

nchildren = len(children)

outer = _GatheringFuture(children, loop=loop)

nfinished = 0

results = [None] * nchildren

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值