Futures and Tokio
This article was originally published at https://gist.github.com/joepie91/bc2d29fab43b63d16f59e1bd20fd7b6e. It may be out of date.
Event loops
If you're not familiar with the concept of an 'event loop' yet, watch this video first. While this video is about the event loop in JavaScript, most of the concepts apply to event loops in general, and watching it will help you understand Tokio and Futures better as well.
Concepts
- Futures: Think of a
Futurelike an asynchronousResult; it represents some sort of result (a value or an error) that will eventually exist, but doesn't yet. It has many of the same combinators as aResultdoes, the difference being that they are executed at a later point in time, not immediately. Aside from representing a future result, aFuturealso contains the logic that is necessary to obtain it. AFuturewill 'complete' (either successfully or with an error) precisely once. - Streams: Think of a
Streamlike an asynchronousIterator; like aFuture, it represents some sort of data that will be obtained at a later point in time, but unlike aFutureit can produce multiple results over time. It has many of the same combinators as anIteratordoes. Essentially, aStreamis the "multiple results over time instead of one" counterpart to aFuture. - Executor: An
Executoris a thing that, when you pass aFutureorStreaminto it, is responsible for 1) turning the logic stored in theFuture/Streaminto an internal task, 2) scheduling the work for that task, and 3) wiring up the Future's state to any underlying resources. You don't usually implement these yourself, but use a pre-madeExecutorfrom some third-party library. The exact scheduling is left up to the implementation of theExecutor. .wait(): A method on aFuturethat will block the current thread until theFuturehas completed, and that then returns the result of thatFuture. This is an example of anExecutor, although not a particularly useful one; it won't allow you to do work concurrently.- Tokio reactor core: This is also an
Executor, provided by the Tokio library. It's probably what you'll be using when you use Tokio. The frontpage of the Tokio website provides an example on how to use it. futures_cpupool: Yet anotherExecutor; this one schedules the work across a pool of threads.
No Comments