Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado difference between run in executor and defining async methods

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.

like image 593
Lore Avatar asked Mar 28 '26 19:03

Lore


1 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.

like image 171
Uku Loskit Avatar answered Mar 31 '26 10:03

Uku Loskit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!