python - 循环后发布 2 个作业的 python asyncio 信号量
问题描述
我需要使用信号量或一些锁来解决两个异步作业的问题。我需要在每个作业的 while 循环中将控制权从一个传递到另一个。第一个作业永远运行,第二个作业最终将完成。
async def my_worker1(semaphore):
n = random.randint(2, 10)
while n > 0:
n -= 1
async with semaphore:
print("Acquired the worker 1")
await asyncio.sleep(2)
print("Releasing worker 1")
async def my_worker2(semaphore):
while True:
async with semaphore:
print("Acquired the worker 2")
await asyncio.sleep(2)
print("Releasing worker 2")
async def main():
my_semaphore = asyncio.Semaphore()
await asyncio.wait([my_worker1(my_semaphore), my_worker2(my_semaphore)])
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print("All Workers Completed")
loop.close()
但是在我的代码中,只有两个工作中的一个工作,并且在当前工作完成之前不会释放信号量。
Acquired the worker 2
Releasing worker 2
Acquired the worker 2
Releasing worker 2
Acquired the worker 2
Releasing worker 2
...
我需要这样的东西:
Acquired the worker 2
Releasing worker 2
Acquired the worker 1
Releasing worker 1
Acquired the worker 1
Releasing worker 1
Acquired the worker 2
Releasing worker 2
...
对不起,如果我的问题不够清楚。
解决方案
我发现了如何解决这个任务。问题是我没有await
可以在每次循环后将控制权传递给另一个工人的结构。工作代码如下所示:
async def my_worker1(semaphore):
n = random.randint(2, 10)
while n > 0:
n -= 1
async with semaphore:
print("Acquired the worker 1")
await asyncio.sleep(2)
print("Releasing worker 1")
await asyncio.sleep(0) # <---
async def my_worker2(semaphore):
while True:
async with semaphore:
print("Acquired the worker 2")
await asyncio.sleep(2)
print("Releasing worker 2")
await asyncio.sleep(0) # <---
推荐阅读
- javascript - addEventListener 中的变量不起作用
- scala - 如何初始化类型别名的空映射
- mysql - Laravel 查询生成器联合:添加“表名”列
- azure-active-directory - 如何在单个请求中使用 MS Graph 获取组织中的所有用户及其成员组
- android - 按双精度对 JSONObjects 的 ArrayList 进行排序不起作用
- type-conversion - Access 2016 中的一个字段中的多个值转换
- swift - Google Speech to Text iOS 应用示例:无法构建模块“googleapis”
- iteration - 如何通过 Openpyxl 中的行简化迭代?
- html - 使用
- ruby-on-rails - Rails 5.2 ActiveStorage 白名单参数