TransWikia.com

Tornado difference between run in executor and defining async methods

Stack Overflow Asked by Lore on November 7, 2021

I am pretty new to Tornado. I can’t understand the difference between using run_on_executor and defining an async method. Is it the same? Is the one multithreaded and the other not?

Thank you in advance.

2 Answers

run_on_executor is for interfacing with blocking non-async code.

You are correct that async code is only executed in a single thread. Maybe an example would illustrate the point.

Let's say your Tornado web service interfaces with a library that makes use of requests to fetch country info for a given IP address. Since requests is a non-async library, calling this function would block the Tornado event loop.

So, you have two options: try to find the replacement for the library that is async-compatible OR run the blocking code in a different thread/process and have your event loop await its result like for normal async code without blocking the event loop. The latter option is run_on_executor which allows you to run the task in different thread or process, and asyncio would "await" its completion.

Answered by Uku Loskit on November 7, 2021

From the docs

Utilities for working with Future objects.

Tornado previously provided its own Future class, but now uses asyncio.Future. This module contains utility functions for working with asyncio.Future in a way that is backwards-compatible with Tornado’s old Future implementation.

While this module is an important part of Tornado’s internal implementation, applications rarely need to interact with it directly.

As I understand run_on_executor from tornado.concurrent is a way of interacting with asyncio.Future with backwards compatibility to old Tornado's Future

In any case, any code based in asyncio is not using multithreading, it's using coroutines

This medium post may help you understand the differences between asyncio and threads: here

Answered by David Bros on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP