简体   繁体   English

如何限制aiofiles的并发读/写数?

[英]How to limit the number of concurrent read / write with aiofiles?

My program would concurrently download about 10 million pieces of data with aiohttp and then write the data to about 4000 files on disk.我的程序会同时使用aiohttp下载大约 1000 万条数据,然后将数据写入磁盘上大约 4000 个文件。

I use the aiofiles library because I want my program to also do other stuff when it is reading/writing a file.我使用aiofiles库是因为我希望我的程序在读/写文件时也做其他事情。

But I worry that if the program try to write to all of the 4000 files at the same time, the hard disk can't do all the writes that quickly.但我担心如果程序试图同时写入所有 4000 个文件,硬盘无法快速完成所有写入。

Is it possible to limit the number of concurrent writes with aiofiles (or other library)?是否可以限制 aiofiles(或其他库)的并发写入数量? Does aiofiles already do this? aiofiles 已经这样做了吗?

Thanks.谢谢。

test code:测试代码:

import aiofiles
import asyncio


async def write_to_disk(fname):
    async with aiofiles.open(fname, "w+") as f:
        await f.write("asdf")


async def main():
    tasks = [asyncio.create_task(write_to_disk("%d.txt" % i)) 
             for i in range(10)]
    await asyncio.gather(*tasks)


asyncio.run(main())

You can use asyncio.Semaphore to limit the number of concurrent tasks.您可以使用asyncio.Semaphore来限制并发任务的数量。 Simply force your write_to_disk function to acquire the semaphore before writing:只需强制您的write_to_disk函数在写入之前获取信号量:

import aiofiles
import asyncio


async def write_to_disk(fname, sema):
    # Edit to address comment: acquire semaphore after opening file
    async with aiofiles.open(fname, "w+") as f, sema:
        print("Writing", fname)
        await f.write("asdf")
        print("Done writing", fname)


async def main():
    sema = asyncio.Semaphore(3)  # Allow 3 concurrent writers
    tasks = [asyncio.create_task(write_to_disk("%d.txt" % i, sema)) for i in range(10)]
    await asyncio.gather(*tasks)


asyncio.run(main())

Note both the sema = asyncio.Semaphore(3) line as well as the addition of sema, in the async with .请注意sema = asyncio.Semaphore(3)行以及在async with中添加的sema,

Output:输出:

"""
Writing 1.txt
Writing 0.txt
Writing 2.txt
Done writing 1.txt
Done writing 0.txt
Done writing 2.txt
Writing 3.txt
Writing 4.txt
Writing 5.txt
Done writing 3.txt
Done writing 4.txt
Done writing 5.txt
Writing 6.txt
Writing 7.txt
Writing 8.txt
Done writing 6.txt
Done writing 7.txt
Done writing 8.txt
Writing 9.txt
Done writing 9.txt
"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM