Тёмный

Intro to async/.await in Rust 

Let's Get Rusty
Подписаться 127 тыс.
Просмотров 88 тыс.
50% 1

In today's video I'm diving into the async/.await model in Rust!
#rust #programming #tutorial

Опубликовано:

 

20 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 132   
@letsgetrusty
@letsgetrusty 2 года назад
📝Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet
@andyvarella6336
@andyvarella6336 Год назад
Can you check the email is going out. I submitted a request twice for the bootcamp and cheatsheet and didn't get email on either one. I checked the spam folder already. 😁Thanks.
@kinositajona
@kinositajona 2 года назад
A sink and a weight are things you find at a gym.
@meqativ
@meqativ 2 года назад
Also rarely spawns in houses
@NieLL1
@NieLL1 Год назад
You make the best videos on Rust I've seen. Most others, even on this specific subject, just talk fast and gloss over dozens of things, whereas you explain things as if you actually want me to have a chance at writing this code myself later. Thanks for the quality content!
@Musikur
@Musikur 2 года назад
Can you show us how to make an implementation of what a simple runtime might look like. Otherwise great video
@riccardot
@riccardot 2 года назад
If you look for the "async" page on the Tokio tutorial, it will teach you how to write a minimal runtime.
@bsd0daemon
@bsd0daemon 2 года назад
I second this!
@echobucket
@echobucket Год назад
@@riccardot I was just about to ask this... thanks!
@massimo79mmm
@massimo79mmm 6 дней назад
i watched a lot of videos and have read a lot of tutorials but all of these tell about “how to implement an echo server with tokio”, bot explaining how it works. your video in a few minutes explains perfectly how it works.
@mageprometheus
@mageprometheus 2 года назад
A very clear description of the tip of the iceberg. I've finally sat through Jon Gjengset's videos and my head is full to bursting. Keep going, these are great.
@J-Kimble
@J-Kimble 2 года назад
Woah, excellent explanation of the async workflow! I always got confused with the tokio stuff, but you've built it up so nicely that it made perfect sense by the time it came up in the video!
@leokiller123able
@leokiller123able Год назад
what is the point of having async functions in standard library if they can't by default be executed asynchronously
@kwabenaboadu
@kwabenaboadu 2 месяца назад
Love how you breakdown the concepts here. Really enjoyed it.
@jongeduard
@jongeduard Год назад
Thanks! Answers a lot of questions for me at the point where I am now. I'm coming from many years of working with C# (and several other languages, but async await is especially important in C#). I have started learning Rust and I've alread gone through the entire official Rust book too (which comes with a manually written ThreadPool example with a mini HTTP server), but that doesn't talk about async await yet. I really like that you can configure the threading behaviour of the tokio library. In C# this behaviour is much more contextual, based on whether you have a so called SynchronizationContext, which is the case in UI frameworks, but not in console applications. In a UI framework you get single threaded behaviour by default for async code, so that you get less issues with cross thread access on the UI, but the risk on deadlocks is higher if you do things incorrectly. Though sometimes you want to configure things per method call, in order to overrule that single threaded continuation behaviour. Does Rust or the tokio library also serve an equivalent of ConfigureAwait?
@stevenhe3462
@stevenhe3462 2 года назад
tokio = { version = "*", features = ["rt-multi-thread", "macros"] } to reduce compilation time
@MuhammedFurkanEkici
@MuhammedFurkanEkici 10 месяцев назад
It's late at night, I am sleepy af and struggling with the words like async/await. Now I realize how beutiful you explain. It is a work of art, and a fine one if I say so myself.
@Ma1ne2
@Ma1ne2 2 года назад
This was so helpful! I was so confused that async is a rust keyword but then everywhere they tell you need some runtime as a crate, since it is not part of the std. Like what? Very confusing for a beginner, but your video explained this greatly! I would like to see more videos about these kind of interactions, maybe how the microcontroller ecosystem is build with HALs etc if you know more about that :)
@TheTavaro11
@TheTavaro11 2 года назад
Thanks for the in depth explanations and not only showing how it can be done :)
@shadowangel8005
@shadowangel8005 Год назад
This was a very clear guide to the basics, I was struggling with why I needed something like tokio. Opening new threads, channels makes since to not block the main thread.
@andyvarella6336
@andyvarella6336 Год назад
I appreciate the great explanation on the feature and how to properly use it. I am looking forward to the bootcamp. Thanks.
@krtirtho
@krtirtho 2 года назад
Just like I always say, Async Rust makes Multi-threading look easy
@danvilela
@danvilela 2 года назад
better than go? just want to know
@elnur0047
@elnur0047 2 года назад
how is it making multi-threading look easy when it pretty much runs on a single thread?
@bjugdbjk
@bjugdbjk 2 года назад
@@danvilela Async code is easy in Go compare to rust, its less verbose, but one thing problem in Go there is a chance of the code ending up in race condition and importantly some issue related to threading gets caught only in runtime in Go which is a extremely costly when u have things in production, Coming to rust, Compiler is extremely strict and if the code gets compiled without any issues for sure 99% there will not be issues in the runtime which is fantastic for rust and race conditions is no where possible in rust.
@SatumangoTheGreat
@SatumangoTheGreat Год назад
@@elnur0047 just a novice myself, but it depends on the runtime you choose, I believe. Tokyo in this case but there are others. And he actually mentions in the video that Tokyo uses a thread pool to run the tasks, so it should enable real parallelism.
@GetfitStoreOfficial
@GetfitStoreOfficial 2 года назад
Thanks for the content. A video about dependencies management (versions, futures) will be great.
@deNudge
@deNudge Год назад
Whenever I see this "async" polluting codebases, I feel thankful for the simplicity of the "go" keyword.
@diadetediotedio6918
@diadetediotedio6918 Год назад
It is not pollution
@porky1118
@porky1118 Год назад
Very informative. Now I finally understand what async really is.
@littlepigism
@littlepigism 2 года назад
Flawless explanation! Really great video. Thanks a lot 🙏
@MrEW1985
@MrEW1985 Год назад
It is quite amazing that a low level language can do the stuff c# does. As a Microsoft specialist I wont be programming Rust anytime soon for my clients but it is certainly nice to know that this kind of stuff is possible.
@uwuzote
@uwuzote 2 года назад
Huge thanks for such awesome video, i will be waiting for advanced async code in next video!
@ESArnau
@ESArnau 2 года назад
What a great video Bogdan, keep it up!
@bjugdbjk
@bjugdbjk 2 года назад
Thank you for providing a glimpse of running native async functions using the community's best runtime Tokio. Could you make a video on "streams and select ", these are quite confusing and I don't see documentation doesn't cover them in a straightforward way, ur videos on these could be a great help ........Thanks again for the amazing content.
@andredasilva6807
@andredasilva6807 2 года назад
love your channel. i was always intrested in rust. but with your videos i feel like i have to use it for everything. its such a nice language. not easy, but really nice. i usually program in python for work. but hope to introduce rust for other stuff in my company
@eduardofernandezdiaz5264
@eduardofernandezdiaz5264 Год назад
Best async await video on the www
@uquantum
@uquantum 2 года назад
Thanks so much...for those like me beginning async in Rust, you helped a lot. Made so much easier as you point out parallels with generally more familiar languages (for Rust newcomers). Perhaps worth noting is that React similarly doesn't let you call await unless the function is async. Loved the intro to Tokio illustrating how it solves a previously unmet need.
@dartme18
@dartme18 Год назад
"Perhaps worth noting is that React similarly doesn't let you call await unless the function is async." He does note that, I think more than once.
@mitigamespro8757
@mitigamespro8757 8 месяцев назад
@@dartme18 I thought you were gonna make a remark on how they said "React" and not Javascript...
@dartme18
@dartme18 8 месяцев назад
​@@mitigamespro8757 You're right, await is a javascript mechanism, not react 😀
@kiransingh2935
@kiransingh2935 2 года назад
Aren't we all just awaiting the future....
@julkiewicz
@julkiewicz Месяц назад
I straight up will never get over how the guy pronounces "cheet sheet"
@workflowinmind
@workflowinmind 2 года назад
Requested it a few days ago perfect timing thanks a lot
@goodwish1543
@goodwish1543 2 года назад
Wonderful! Looking forward for more Tokio sessions. Thanks.
@RufusROFLpunch
@RufusROFLpunch 2 года назад
Great video, as usual. Even when it's a concept I already understand, I appreciate the refresher with a clear communication style. Unrelated, but I want to ask if you have been working on your accent? With each video it becomes more indistinguishable from a regular American accent. I'm just curious if that is natural, or if it is intentional? Pretty good, either way!
@Pg1668
@Pg1668 Год назад
The for loop in lines 15-17 (for handle in handles) makes me think you're sequentially calling await. How does it execute concurrently?
@MadMathMike
@MadMathMike 10 месяцев назад
Fantastic content
@Beiri22
@Beiri22 2 года назад
follow-up question - what about the state / future of generators?
@alexandershemelin6605
@alexandershemelin6605 2 года назад
Nicely explained, thank you.
@everyhandletaken
@everyhandletaken 2 года назад
My nodejs brain was doing fine, until you started getting all concurrent 😂 Great video though, helps a lot!
@thekwoka4707
@thekwoka4707 Год назад
I was hoping for a bit more showing how the actual runtime/executor works. Like how does the polling process actually work?
@joelimbergamo639
@joelimbergamo639 2 года назад
Is there an equivalent of the .then JS syntax ? If you don't want to await but you want to execute some code after the future returned how do yoy do it? Do you need to create an async function and call await there as you did in the video?
@gzoechi
@gzoechi Год назад
Excellent explanation 🚀
@mayankchauhan6680
@mayankchauhan6680 Год назад
Great! this will take a bit effort to absorve. I tried an experiment with read_from_database and generated a random number using rand library to use as argument in sleep method. But rust started complaining as it said 'mut rng' of Rng does not implement Send traid and can not be passed across threads.
@omermarom6592
@omermarom6592 Год назад
Great video! One thing I didn't understand was why I should not put performance intensive calculations in async functions. Obviously if I'm using the single threaded mode (flavor=current_thread) then yeah it'll hold up the entire event queue, but if it's multithreaded then other threads can continue executing while the calculation is being done. Any help would be appreciated! 🙏
@David-x7u6k
@David-x7u6k Год назад
If you run long running task on async task, it will prevent another task in same worker(thread) to make progress. In tokio, There is two option to run long running task without impacting overall performance. 1. block_in_place: It will move every task in current worker thread to another worker thread but self. 2. spawn_blocking: It will move long running task to dedicated blocking thread pool and put current task into sleep until long running task completes.
@MrDujmanu
@MrDujmanu 7 месяцев назад
@@David-x7u6k Very good question and answer too, I had the same problem. Thank you.
@_jdfx
@_jdfx 2 года назад
amazing content, thanks Bogdan!
@someon3
@someon3 Год назад
In C++ you can spawn a task (or just return one from a function) with std::async and C# has its own executor to spawn a new task as soon as you call an async method, rust takes both of them to make it more verbose and pointless, so i'm still tryna understand the real benefits of using async/await in Rust and not just simple thread spawning as in C++
@SumoCumLoudly
@SumoCumLoudly Год назад
There's absolutely no benefit to using rust over c++ unless you don't understand allocating memory. You would think with rust being a modern language it would make things simpler and cleaner than c++ but the opposite is true.
@PeterAuto1
@PeterAuto1 Год назад
spawning threads is expensive. If you have many tasks which are IO bound, asyinc/await will be faster than if you spawn a thread for each.
@diadetediotedio6918
@diadetediotedio6918 Год назад
@@SumoCumLoudly I'd say the opposite, there's simply no point in using C++ in almost any scenario rather than using Rust, it's just dumb and needlessly bugging you.
@redcrafterlppa303
@redcrafterlppa303 Год назад
​@@SumoCumLoudly saying that you can code as safe in c++ as in rust by "understanding allocating memory" is undermining the fact that the majority of bugs to this day come from poorly managed memory. Even the top c++ gods write memory leaks amd out of bounds errors period. Thinking that you can write programs that are somewhat bigger than a student works in c++ without creating a single memory error somewhere is ludicrous. Many of the leading tech companies call c++ a sinking ship while simultaneously rewriting buggy c++ code in rust.
@Cookiekeks
@Cookiekeks Год назад
@@SumoCumLoudly Why make your life more difficult worrying about memory management in C++, when you can simply use Rust and let the compiler tell you how to write safe code?
@minneelyyyy
@minneelyyyy Год назад
him: in this example we have two functions me: whoa slow down there
@Willkillson180
@Willkillson180 7 месяцев назад
Its odd to me that the keywords in the language can't be utilized within the standard library, and we need a community led package to use. I do see the mini_tokio implementation, but why can't this be in the std lib?
@ShrirajHegde
@ShrirajHegde Год назад
I'm curious why the await functionality is used by syntax future.await not await future
@travisarndt853
@travisarndt853 Год назад
They got some inspiration from C#
@affegpus4195
@affegpus4195 Год назад
You say you shoulnt put cpu intensive operations in async code. lets say have a big list of elements that need to be processed. Is making my function that processes them async and sending slices of the list to it so it runs can run concurrently a bad idea?
@diadetediotedio6918
@diadetediotedio6918 Год назад
nop
@fabianrigo4168
@fabianrigo4168 7 месяцев назад
Having to add a dependency just to add async code kinda sucks, doesnt it? Im new to Rust, comming from c#. I know its a minor thing, but i like to keep my dependencies as few as possible, and i dont realy see why this isnt in the base rust functionality? A Explanation would be great, cause i dont see how this makes sense tbh.
@d0lvl0
@d0lvl0 2 года назад
Is it possible to use a debugger with asyc rust, and have breakpoints get triggered inside async functions?
@peternierop3241
@peternierop3241 2 года назад
4:50 you describe await as a callback to the executor. I might be mistaken, however I seem to be told that the executor polls rather that establishing a callback... ??
@jakob2946
@jakob2946 2 года назад
I dont understand the await/async is nessesary for this. Using threads/tokyo should add the concurrency. Why was the async and await nessesary.
@joestogner5233
@joestogner5233 2 года назад
Same question
@affegpus4195
@affegpus4195 Год назад
From what i understand. With this you can run non blocking functions concurrently without thread spawning costs, no worry about scheduling, with code that looks just like the single thread ine.
@jakob2946
@jakob2946 Год назад
@@affegpus4195 oka i think that makes sense thx
@liberalwrecker949
@liberalwrecker949 Год назад
Call me crazy but you still have to await the “handle” to get the result of the async function. So wrapping them in tokio::spawn() is just extra boilerplate when you could just write my_function().await which you also still have to do inside of tokio::spawn() anyways. The only thing tokio seems to be actually doing is wrapping the future in a result
@redcrafterlppa303
@redcrafterlppa303 Год назад
As far as I understood it Tokyo spawn takes a (lazy) future, starts running it without returning control flow to the caller allowing you to start other work that runs in parallel to the started future (potentially another future). Awaiting 2 futures after another is running the 2nd after the first completed. Running 2 futures with Tokyo spawn will start their execution simultaneously making them run at the same time and then collecting the result of the 2 parallel run futures when awaiting their handles.
@meka4996
@meka4996 Год назад
When you say "concurrently", did you mean "running parallelly in threads" ?
@arubaga
@arubaga 4 месяца назад
The static lifetime on the async has bad usability. Ease of debug was bad as well. The main purpose of async / await was for no wait I/O, and you just as well use such a no wait IO crate directly.
@paoloposso
@paoloposso Год назад
Can you create or, if you already have, or is to a video with an example of how to for and forget tasks? Also when you use async move, when the type is not Send, it’s not that easy (having this kind of trouble right now)
@MrDujmanu
@MrDujmanu 7 месяцев назад
Newb here: at 9:55, when calling tokio::spawn(..) why is there a need to use the async move block? Isnt' tokio::spawn(my_function(i)) a legal call? my_function already is a future.
@AceofSpades5757
@AceofSpades5757 2 года назад
Awesome! Moar asyncio!
@fr3dr
@fr3dr 2 года назад
thanks!
@kotreq5862
@kotreq5862 Год назад
How do you get realtime error side to your code, i can't seem to make vs code check my code more than only on save
@AykutKlc
@AykutKlc Год назад
Very good video indeed.
@coldsir5406
@coldsir5406 2 года назад
Hi, how to test those async functions? Let's say i have a module with some async functions which I'll use into my web-server (actix) service. How to test them independently?
@piotrkrzyzaniak8933
@piotrkrzyzaniak8933 Год назад
Thanks a lot man!
@Xaxxus
@Xaxxus Год назад
its a bit strange that rust has async and await built in, but not an async runtime.
@JonathanLoscalzo
@JonathanLoscalzo 2 года назад
I'm learning (or watching at least) rust with you. I don't know if it will be the super future language or not, but you keep me entertained. I need some more practical courses, do you have other practical courses? like some ebook or udemy? It will be a good idea!
@GlobalYoung7
@GlobalYoung7 2 года назад
Thank you 😊
@timvw01
@timvw01 2 года назад
Good video !
@erlangparasu6339
@erlangparasu6339 2 года назад
Thanks!
@KresnaPermana
@KresnaPermana 2 года назад
Why there is a *move* keyword at closure async function?
@williamwatkins6669
@williamwatkins6669 Год назад
tokio mentions that the sleep function is limited to a millisecond granularity. What would you use to sleep for microseconds? i looked at tokio-timerdf but there's very little examples and i'm quite new (fyi, running on linux) thanks
@redcrafterlppa303
@redcrafterlppa303 Год назад
You need to understand the control flow of calling sleep : Sleep is awaited Sleep finished and calls the wake method of the Tokyo runtime Tokyo registers that the future in which sleep was called should now be pulled again to execute the code after sleep. This happens (likely) by enquing the future in a queue that the Tokyo runtime is working to clear. By stepping through this you can see that there are multiple points where the duration it takes to execute the things after sleep can be delayed by things unrelated to sleep and you current function (like other awaited futures in the set queue before the sleep one). In short you cannot predict how long it will take sleep to return exactly and the tokyo team decided that a finer grain of delay is impossible to guarantee. Imagine waiting for 5.05 milliseconds and then being stuck in the queue for a minimum of 1 millisecond. What is the point in these 0.05 milliseconds then?!
@mattxyzeth
@mattxyzeth Год назад
2:16 giggity
@JorgetePanete
@JorgetePanete Год назад
Which are the reasons for not wanting cpu-intensive code in async functions?
@diadetediotedio6918
@diadetediotedio6918 Год назад
Because it's still just programming code, the benefits of asynchronous programming is that you can "wait" and thereby leverage all threads in an equivalent way, if you run a lot of sequential code (no await or yield) in an async method it will be basically blocking a thread for a long time
@browaruspierogus2182
@browaruspierogus2182 Год назад
Looks like Rust is a language where you have to memorize so so much what one tiny statement does - isn't is a big disadvantage?
@debuti
@debuti 2 года назад
Nice, but how is this different from a regular thread oriented program?
Год назад
What is your opinion to async_std?
@vincent-thomas
@vincent-thomas 2 года назад
Why should we not put cpu intensive tasks in async functions?
@joelimbergamo639
@joelimbergamo639 2 года назад
Bc async is ment to share execution time between all async functions. If you have cpu intensive tasks you should spawn a new thread in order to use another core of the CPU.
@richsadowsky8580
@richsadowsky8580 2 года назад
whenever I type in these programs I get errors. For example, I have exactly what you show but I get an error trait Future { type Output; fn poll(&mut self, wake: fn()) -> Poll; } enum Poll { Ready(T), Pending, } fn my_function() -> impl Future { println!("I'm an async function"); } Same code as far as I can tell, but VC Code is underlining the "impl Future" saying the trait `Future` is nit implemented for `()`. This type of error is in almost every program I type in. I wish there was source code I could paste in to avoid typing errors. Why do none of the examples work? Guessing game worked but i had to make a few changes. I am on cargo: cargo 1.61.0 (a028ae42f 2022-04-29) and rustc: rustc 1.61.0 (fe5b13d68 2022-05-18). I really want to use the language but none of your examples work correctly. Do I have something misconfigured? This is driving mr crazy!!!
@richsadowsky8580
@richsadowsky8580 2 года назад
likewise can someone recommend example tutorials where the code works and has sample code to paste in? I like Bogdan's style but literally none of the programs work without some bizarre error
@nayyaraairlangga321
@nayyaraairlangga321 2 года назад
Not a tutorial, but the Rust books have great examples. They walk you through pretty much the process of how the code is how it is so you may get a feel on it. For async, I’d recommend reading the Asynchronous Programming in Rust book. It’s a pretty solid guide to async in Rust. It’s pretty short and concise
@richsadowsky8580
@richsadowsky8580 2 года назад
@@nayyaraairlangga321 Thanks man. I haven't bought that one yet. I'm old school and still enjoy using a good old fashioned book to learn new languages. But I wonder why whenever I type in one of LetsGetrusty's code from off his screen it is always not working quite right. I would love to find typed in code to see if there's something I mistyped but don't see. That is usually the root cause
@usaaccount1179
@usaaccount1179 2 года назад
must make a video on async streams with tokio
@DavidAlsh
@DavidAlsh 2 года назад
Are async closures still unstable?
@sajinijayasinghe3282
@sajinijayasinghe3282 2 года назад
go into shortcuts in tNice tutorials video. They are not technically linked but it's close. I do wish there was a way to completely link them
@kamalkamals
@kamalkamals 2 года назад
u need to add error handler
@10inall28
@10inall28 2 года назад
More async stuff
@sc5shout
@sc5shout Год назад
Why tokio::spawn takes ownership of the i variable? I mean, i is allocated and assigned to 0, then spawn takes the ownership of i, so i is no longer valid for the next loop iteration, meaning i may be pointing to a nullptr or the memory region that is already in use.
@porky1118
@porky1118 Год назад
These inlay hints of visual studio are always so annoying.
@ИнякинАлександр
@ИнякинАлександр 2 года назад
Ничего не понял, но очень интересно.
@tomburg2
@tomburg2 2 года назад
С какой целью ты смотрел видео? С чисто художественной или с образовательной (изучение языка rust)?
@duckmasterflex
@duckmasterflex 2 года назад
Ha polled to completion
@matrixdev
@matrixdev 2 года назад
Here is an unpopular idea - maybe someone someday will show how to use async Rust without libraries in the real world?.. Because at this point all videos can be broken down to tokio advertisement rather than actual async Rust. General idea for async/await is more or less the same for all languages, the difference only comes down to built-in runtimes and rust doesn't have one. Tokio is great, but it is not the best solution for every project and it would be really nice to learn different approaches for using async Rust or writing own single and multithreaded runtimes.
@affegpus4195
@affegpus4195 Год назад
he pretty much said that you need a runtime to make it work. The language doesn't provide its own async runtime, just a way to call them
@rad9587
@rad9587 2 года назад
Спасибо за видео. Если не трудно, мог бы ты делать субтитры на русском? Русскоговорящие бы в таком случае смогли бы и английский подтянуть, и лучше воспринимать информацию. Был бы очень благодарен:)
@НазарПогорелов-н2б
Здравствуйте. Вы можете скачать яндекс браузер и слушать видео на русском языке)
@tomburg2
@tomburg2 2 года назад
А что этот мужик знает русский язык?
@rad9587
@rad9587 2 года назад
@@tomburg2 он Украинец
@lmaoez2020
@lmaoez2020 2 года назад
он русский?
@CiutyGhr
@CiutyGhr 2 месяца назад
cringe
Далее
8 deadly mistakes beginner Rust developers make
14:14
Просмотров 167 тыс.
Async Rust Is A Bad Language | Prime Reacts
28:46
Просмотров 96 тыс.
Ромарио стал Ромой
00:46
Просмотров 308 тыс.
The Async Await Episode I Promised
12:04
Просмотров 1,1 млн
All Rust string types explained
22:13
Просмотров 171 тыс.
State Pattern in Rust | Rust Language
20:21
Просмотров 1,7 тыс.
but what is 'a lifetime?
12:20
Просмотров 72 тыс.
Async Rust Is The Bane Of My Existence | Prime Reacts
35:36
Strings in Rust FINALLY EXPLAINED!
21:40
Просмотров 76 тыс.
Solving distributed systems challenges in Rust
3:15:52
Просмотров 238 тыс.