我试图理解 asyncio 模块并花了大约一小时使用 run_coroutine_threadsafe 函数,我什至来到了工作示例,它按预期工作,但有一些限制。
首先,我不明白应该如何在主(任何其他)线程中正确调用 asyncio 循环,在示例中我调用它并run_until_complete
给它一个协程以使其忙于某些事情,直到另一个线程不会给它一个协程。我还有什么其他选择?
在现实生活中,什么情况下我必须混合使用异步和线程(在 Python 中)?据我了解,asyncio 应该取代 Python 中的线程(由于 GIL 不是 IO 操作),如果我错了,请不要生气并分享您的建议。
Python版本为3.7/3.8
import asyncio
import threading
import time
async def coro_func():
return await asyncio.sleep(3, 42)
def another_thread(_loop):
coro = coro_func() # is local thread coroutine which we would like to run in another thread
# _loop is a loop which was created in another thread
future = asyncio.run_coroutine_threadsafe(coro, _loop)
print(f"{threading.current_thread().name}: {future.result()}")
time.sleep(15)
print(f"{threading.current_thread().name} is Finished")
if __name__ == '__main__':
loop = …
Run Code Online (Sandbox Code Playgroud) python multithreading asynchronous python-3.x python-asyncio
我试图限制使用信号量同时运行的异步函数的数量,但我无法让它工作。我的代码归结为:
import asyncio
async def send(i):
print(f"starting {i}")
await asyncio.sleep(4)
print(f"ending {i}")
async def helper():
async with asyncio.Semaphore(value=5):
await asyncio.gather(*[
send(1),
send(2),
send(3),
send(4),
send(5),
send(6),
send(7),
send(8),
send(9),
send(10),
])
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(helper())
loop.close()
Run Code Online (Sandbox Code Playgroud)
输出是:
starting 1
starting 2
starting 3
starting 4
starting 5
starting 6
starting 7
starting 8
starting 9
starting 10
ending 1
ending 2
ending 3
ending 4
ending 5
ending 6
ending 7
ending 8
ending 9
ending …
Run Code Online (Sandbox Code Playgroud) 我有 mxn 网格。米 >= 1 ; n >= 1
我在左上角有项目,需要到达网格的右下角。
项目只能向下或向右移动。
我需要找到可能的独特路径来做到这一点。
我针对这个问题做了两个解决方案:递归(比下面一个慢)和下面一个。
问题是当 m 和 n 很大时我的内存不足,例如 m == 20 和 n >= 15(使用了超过 4 Gb - 我拥有的所有可用内存)。
我怎样才能改进我的解决方案,或者应该有绝对的其他方法来解决这个问题?
def unique_paths(m, n):
assert isinstance(m, int), "m should be integer"
assert isinstance(n, int), "n shoudl be integer"
assert m >= 1, "m should be >= 1"
assert n >= 1, "n should be >= 1"
if m == 1 and n == 1: # border case
return 1
ch = …
Run Code Online (Sandbox Code Playgroud)