Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python tornado';在创建异步子例程时运行同步?_Python_Asynchronous_Tornado - Fatal编程技术网

如何使用Python tornado';在创建异步子例程时运行同步?

如何使用Python tornado';在创建异步子例程时运行同步?,python,asynchronous,tornado,Python,Asynchronous,Tornado,我想使用tornado IOLoop的run\u sync运行一个方法,该方法启动异步方法 我的想法是: @gen.coroutine def async(string): print string @gen.coroutine def sync(): string_list = yield async_call() for string in string_list: async(string=string) loop = IOLoop.curre

我想使用tornado IOLoop的run\u sync运行一个方法,该方法启动异步方法

我的想法是:

@gen.coroutine
def async(string):
    print string


@gen.coroutine
def sync():
    string_list = yield async_call()
    for string in string_list:
        async(string=string)

loop = IOLoop.current()
loop.run_sync(lambda: sync)

因此,同步中的所有内容都需要同步发生,但调用async的顺序并不重要。这在tornado中可能吗?

正如我所见,您误解了异步计算的含义。简而言之,如果有两个函数在IOLoop中异步执行,那么每个函数的代码都将同时执行,但函数的工作流仍然是同步的

当您运行
async
方法而不使用
yield
关键字时,您将成为舒尔,它在调用函数之前完成,尤其是当您使用
run\u sync
时,它会在函数停止后停止IOLoop。当
async
仍在运行但IOLoop停止时,这可能会导致未定义的行为

我已经编辑了您的代码,以显示同步的功能工作流是同步执行的:

@gen.coroutine
def async(string):
    yield gen.sleep(2)
    print string

@gen.coroutine
def async_call():
    return ["one", "two", "three"]

@coroutine
def sync():
    string_list = yield async_call()
    for string in string_list:
        yield async(string)

loop = IOLoop.current()
loop.run_sync(sync)
输出:

$python test_async.py
one
two
three

正如我所看到的,您误解了异步计算的含义。简而言之,如果有两个函数在IOLoop中异步执行,那么每个函数的代码都将同时执行,但函数的工作流仍然是同步的

当您运行
async
方法而不使用
yield
关键字时,您将成为舒尔,它在调用函数之前完成,尤其是当您使用
run\u sync
时,它会在函数停止后停止IOLoop。当
async
仍在运行但IOLoop停止时,这可能会导致未定义的行为

我已经编辑了您的代码,以显示同步的功能工作流是同步执行的:

@gen.coroutine
def async(string):
    yield gen.sleep(2)
    print string

@gen.coroutine
def async_call():
    return ["one", "two", "three"]

@coroutine
def sync():
    string_list = yield async_call()
    for string in string_list:
        yield async(string)

loop = IOLoop.current()
loop.run_sync(sync)
输出:

$python test_async.py
one
two
three

几乎,调用async实际上是调度和执行函数,除非ioloop停止。异步函数需要ioloop才能运行,不管是否生成。使用
yield
时,它将等待异步完成。@kwarunek感谢您的提及,我已经在我的机器上签入了这个,它似乎按照您所说的运行。但有一件事我还不清楚:如果
async
方法需要比
sync
更多的时间来完成,IOLoop将在结束前停止,我真的无法想象
async
是否正确完成。几乎,调用async实际上是在调度和执行函数,除非ioloop停止。异步函数需要ioloop才能运行,不管是否生成。使用
yield
时,它将等待异步完成。@kwarunek感谢您的提及,我已经在我的机器上签入了这个,它似乎按照您所说的运行。但有一件事我还不清楚:如果
async
方法需要比
sync
更多的时间来完成,IOLoop将在结束前停止,我真的无法想象
async
是否正确完成。