Using asyncio to initiate multiple background tasks, when each task is synchronous

Considering you have the following code:

import asyncio
import functools

if __name__ == '__main__':
    asyncio.run(main())


async def main():
    background_t = set()
    for i in range(6):
        task = asyncio.create_task(foo1(i))
        background_t.add(task)

async def foo1(i):
  loop = asyncio.get_running_loop()
  try:
      await asyncio.wait_for(loop.run_in_executor(None, functools.partial(foo2(), i),60)
  except asyncio.TimeoutError:
      print("timed out")

def foo2(num):
  # some blocking code

My question if this pattern causes the code to run concurrently in six different tasks when each of them is synchronous operation.

7

Almost there:

the blocking functions are correctly scheduled to run in different threads in the default executor, and some of those will star running, and execute concurrently.

However, there will be only so many of those tasks running as there are workers in the executor – and each of them will take a full worker for the time it is running. (So, if a task is a continuous loop, with no return, or takes more than 60 seconds, it will simply block a worker).

The OS and Python runtime will switch automatically across all running such tasks (even though due to Python limitations up to 3.12 they will only use a single CPU core at a time, and with a special “free threading” build of 3.13 you can use actual parallelism in various cores for free). The problem is that any task scheduled after all workers are busy won’t start until there is a free worker – it will just be queued for execution.

If the blocking cause is I/O code, just creating an explicit executor with at least as many workers as there are tasks you want to run in parallel will work they way you plan.

A better strategy, if the workers are to be kept running, is to use an explicit thread for each task, with asyncio.to_thread instead.
And keep in mind that the synchronous functions in other threads have no way to be automatically cancelled: even if the awaitable wrapper call (either run_in_executor or to_thread) is cancelled, for example, by timing-out, the actual synchronous code will keep running and using system resources until it finishes naturally.
The only fix for that is to create a state which can be checked inside the sync code (for example, an instance attribute, or a value posted to a Queue (thread-oriented queue from queue.Queue, not asyncio.Queue)

As a side note, Python code in a module is executed in order – you call to the main() function must be at the botton. The if __name__ ... device is not mandatory – it is a thing that Can be used and allows your module to either be importable into a larger project, or run as an standalone app. If it is not meant to be imported, just call main() in the last line, at the module level.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật