为什么没有call_at_threadsafe和call_later_threadsafe?

Spr*_*ple 2 python-3.x python-asyncio

我在Windows 32位中使用Python 3.5.2并且知道asyncio call_at不是线程安全的,因此下面的代码不会打印'bomb',除非我取消注释该行 loop._write_to_self().

import asyncio
import threading


def bomb(loop):
    loop.call_later(1, print, 'bomb')
    print('submitted')
    # loop._write_to_self()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    threading.Timer(2, bomb, args=(loop,)).start()
    loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

但是,我无法找到有关原因call_at_threadsafecall_later_threadsafe实施的信息.这个理由是否存在?

Vin*_*ent 6

只需用于loop.call_soon_threadsafe安排loop.call_later:

loop.call_soon_threadsafe(loop.call_later, 1, print, 'bomb')
Run Code Online (Sandbox Code Playgroud)

  • @SpringMaple这听起来像是过早优化.只要你的程序被正确写入(例如没有阻塞调用),回调就会很快被称为"很快".但是,我认为`_write_to_self`替代方案是可以接受的. (2认同)