首页 > 解决方案 > asyncio 任务是否共享内存?

问题描述

我的 Python 应用程序中有多个异步函数。

这些函数执行读取文件内容、操作和转换为二进制的操作

例如:

async def perform_all(location):
  file_contents = await get_file(location)
  new_file_contents = await manipulate_file(file_contents)
  in_binary = await convert_to_binary(new_file_contents)
  await save(location + '.binary', in_binary)

所有这些单独的功能都是异步的:

async def get_file(location):
   # ... open file, read all and send contents

async def manipulate_file(file_contents):
   # ... do something to the contents like add their lengths together

async def convert_to_binary(new_file_contents):
   # ... given the characters, convert to binary and return it

async def save(location, in_binary):
   # ... save binary in the location

在应用程序启动时,我创建了 5 个任务。
每个任务在perform_all()不同的位置运行函数。该函数perform_all()由在任务中运行的循环每 1 分钟执行一次。它查找文件并将其转换为二进制文件。

如果可以回答,我有几个问题:

  1. 这段代码是异步安全的吗?

  2. 如果不是那么为了理解,我如何使它成为非异步安全的,以便我可以可视化问题?

  3. 这两个任务是否会错误地操作相同的文件内容,或者每个任务都会分配给它自己的内存并且一个任务中的文件内容与file_contents另一个任务中的文件内容不同?

标签: pythonasynchronouspython-asyncio

解决方案


推荐阅读