Latest / CyberCode Academy / Course 19 - Ultimate Rust Crash Course | Episode 5: Rust Concurrency Fundamentals: Closures, Threads, and Channel Communication
Transcript
- 0:00Speaker 1: Welcome back to the deep dive, where we dissect complex
- 0:02Speaker 1: programming concepts to give you the clear, actionable insights you need.
- 0:06Speaker 2: And today we're jumping into a really powerful combination.
- 0:09Speaker 1: We are we're talking about closures and threads. These are
- 0:12Speaker 1: I mean, they're the tools that let modern software be
- 0:15Speaker 1: both expressive, letting you define logic on the fly, and
- 0:19Speaker 1: also incredibly fast.
- 0:21Speaker 2: Right because you can finally use all those CPU cores
- 0:24Speaker 2: that are just sitting there exactly. And I think this
- 0:26Speaker 2: deep dive is really about controlling complexity. It's not just
- 0:30Speaker 2: about what these things are, but it's about the invisible rules,
- 0:34Speaker 2: you know, ownership lifetimes, how data actually moves between these
- 0:39Speaker 2: separate worlds.
- 0:40Speaker 1: Okay, so let's unpack this. Our mission today is to
- 0:42Speaker 1: get our heads around what closures are, how they capture
- 0:45Speaker 1: and manage their data, and why that becomes so critical
- 0:48Speaker 1: when we start talking about the parallel power of threads.
- 0:51Speaker 1: We want to give you a kind of mental roadmap
- 0:53Speaker 1: for building these really robust, high performance concurrent systems.
- 0:57Speaker 2: So let's begin with the closure itself. At its core,
- 1:00Speaker 2: you can just think of it as an anonymous function.
- 1:02Speaker 1: Anonymous so yeah, no name, exactly.
- 1:05Speaker 2: It doesn't have a formal name attached to it. The
- 1:07Speaker 2: key feature is that you can define this little chunk
- 1:09Speaker 2: of logic, assign it to a variable, and then you know,
- 1:13Speaker 2: execute it later. You can even pass it around like
- 1:15Speaker 2: it's a piece of data.
- 1:16Speaker 1: And the syntax is so clean. That's what always strikes
- 1:19Speaker 1: me when you define one. The parameters are just listed
- 1:22Speaker 1: between two vertical pipes that can put data. Yeah, and crucially,
- 1:26Speaker 1: you almost never have to write out the data types
- 1:28Speaker 1: for the arguments or what it returns.
- 1:30Speaker 2: And that's the magic of type inference, right. The compiler
- 1:34Speaker 2: is smart enough to look at how you're using the closure,
- 1:37Speaker 2: what you pass into it, what you do with the result,
- 1:40Speaker 2: and it just figures out all the types.
- 1:42Speaker 1: For you, which makes the code so much less noisy.
- 1:44Speaker 1: You can just focus on the logic exactly. But this
- 1:47Speaker 1: is where it gets more interesting than just a nameless function, right,
- 1:50Speaker 1: the whole data management side.
- 1:52Speaker 2: That is the real distinction of a closure. It captures
- 1:55Speaker 2: its environment. A closure can borrow references to data that's
- 2:01Speaker 2: in the scope where it was defined.
- 2:02Speaker 1: It's enclosing scope.
- 2:03Speaker 2: It's in closing scope. Yeah. So if you have a
- 2:06Speaker 2: string variable declared outside and your closure needs to print it.
- 2:09Speaker 2: It just automatically borrows a reference to that string. It
- 2:13Speaker 2: can use it without taking it away from the original scope.
- 2:15Speaker 1: But borrowing is temporary, and that's where we hit a
- 2:18Speaker 1: huge wall in programming, especially when threads come into the picture.
- 2:22Speaker 2: It is the borrowed data has to outlive the.
- 2:25Speaker 1: Closure always, which can be a problem.
- 2:27Speaker 2: It's the lifetime challenge. If your closure is defined inside
- 2:31Speaker 2: a function and that function ends, what happens. All its
- 2:34Speaker 2: local variables are destroyed. If your closure is still somewhere
- 2:38Speaker 2: holding a reference to that vanished data, well that's a crash.
- 2:42Speaker 1: And if we want to launch that closure onto a
- 2:44Speaker 1: brand new thread, the problem just gets magnified, doesn't it.
- 2:47Speaker 3: Oh?
- 2:47Speaker 2: Absolutely, The new thread runs completely on its own, it
- 2:51Speaker 2: might live way longer than the function that created it.
- 2:53Speaker 2: The compiler sees that danger and just says, nope, it
- 2:56Speaker 2: won't compile if you try to borrow something that might disappear.
- 3:00Speaker 1: Is just too high.
- 3:01Speaker 2: It is, so we need a way to make the
- 3:02Speaker 2: closure completely self sufficient.
- 3:04Speaker 1: Which brings us directly to move semantics.
- 3:06Speaker 2: Precisely, by putting the move keyword right before your closure,
- 3:11Speaker 2: you're giving the compiler a very explicit instruction. You're saying,
- 3:15Speaker 2: I want this closure to take full ownership of any
- 3:18Speaker 2: variables it uses from the outside.
- 3:20Speaker 1: So the variable is literally move.
- 3:22Speaker 2: It's moved into the closure. It now lives and dies
- 3:25Speaker 2: with that closure.
- 3:26Speaker 1: Okay, but there's a trade off here, as in they're saying,
- 3:28Speaker 1: I have a huge vector of data in my main thread.
- 3:32Speaker 1: If I use move to hand it over to a closure,
- 3:36Speaker 1: I immediately lose access to that vector in my main thread.
- 3:40Speaker 1: It's gone. That's a clean transfer, sure, but it feels
- 3:43Speaker 1: like a big constraint if I needed that data later.
- 3:46Speaker 2: It is a critical trade off. Absolutely, you sacrifice the
- 3:49Speaker 2: ability to use the data in the original scope, but
- 3:52Speaker 2: in exchange you get guaranteed memory safety in that new context,
- 3:55Speaker 2: like a thread, and that guarantee is everything. It's why
- 3:58Speaker 2: move closures are the foundation of safety currency. They sort
- 4:01Speaker 2: of package everything up a completely self contained worker, ready
- 4:04Speaker 2: to go.
- 4:04Speaker 1: That makes sense. Okay, so that makes the jump to
- 4:07Speaker 1: threads possible. But before we go there, let's take a
- 4:09Speaker 1: quick look at where closures really shine on their own
- 4:12Speaker 1: In functional programming.
- 4:13Speaker 2: Oh, for sure, closures are the workhorse for processing collections
- 4:17Speaker 2: of data. The moment you call an iterator method on
- 4:19Speaker 2: a vector, you unlock this huge, powerful toolkit for building
- 4:23Speaker 2: functional pipelines.
- 4:24Speaker 1: Right, Let's walk through that classic three step process, map, filter,
- 4:27Speaker 1: and fold to show why this is often so much
- 4:30Speaker 1: better than a plain old four loop.
- 4:32Speaker 2: And the key insight here is that these functional methods
- 4:34Speaker 2: they push you toward immutability by default. That makes your
- 4:38Speaker 2: code way easier to reason about and critically much easier
- 4:41Speaker 2: to parallelize later on.
- 4:43Speaker 1: Okay, step one map. The map method takes a closure
- 4:48Speaker 1: and its whole job is transformation.
- 4:50Speaker 2: Right.
- 4:50Speaker 1: So imagine we have a list of user scores. We
- 4:53Speaker 1: want to convert them, maybe find their square roots. The
- 4:55Speaker 1: map closure defines that one action score score dot sqrt.
- 5:00Speaker 2: And it's worth remembering that often the item that gets
- 5:03Speaker 2: passed into that closure is a reference to the data,
- 5:06Speaker 2: not the data. It's all right, So you might need
- 5:08Speaker 2: to first call something like copied on your iterator to
- 5:11Speaker 2: get actual values, or you know, manually dereference it inside
- 5:15Speaker 2: the closure. But the key is that map takes your
- 5:18Speaker 2: sequence and creates a brand new one of the same length,
- 5:21Speaker 2: with every single element transformed.
- 5:23Speaker 1: Okay, so that's map. Step two filter. Now we want
- 5:27Speaker 1: to thin out the collection.
- 5:28Speaker 2: Right, and filter takes a special kind of closure. It's
- 5:30Speaker 2: called a predicate.
- 5:32Speaker 1: A predicat is just a fancy word for a closure
- 5:34Speaker 1: that returns true or false.
- 5:36Speaker 2: That's all it is. In our score example, the filter
- 5:39Speaker 2: closure might be something like score score fifty. If it's true,
- 5:43Speaker 2: the item stays. If it's false, it's gone. This step
- 5:46Speaker 2: actually shrinks your sequence down.
- 5:48Speaker 1: Okay, And finally step three fold. After mapping and filtering,
- 5:52Speaker 1: we usually want one single result.
- 5:54Speaker 2: An aggregation, yeah, fold needs two things. An initial value
- 5:58Speaker 2: like zero if you're summing things up, and a closure
- 6:01Speaker 2: that explains how to combine the current running total with
- 6:03Speaker 2: the next item.
- 6:04Speaker 1: So you pass it a closure like accumulator item accumulator plus.
- 6:07Speaker 3: Item, and it just churns through all the remaining values
- 6:11Speaker 3: and at the end you get one single number back
- 6:13Speaker 3: the total sum and that whole pipeline map filter fold
- 6:18Speaker 3: is just incredibly efficient and readable.
- 6:21Speaker 1: And that move keyword we talked about makes the closure
- 6:25Speaker 1: self sufficient, which is exactly what the system needs when
- 6:27Speaker 1: we launch it into its own thread exactly.
- 6:30Speaker 2: So now we're transitioning to concurrency. The foundation here is
- 6:33Speaker 2: the thread dot spawn function. To launch a new thread,
- 6:37Speaker 2: you just pass it a closure that takes no.
- 6:39Speaker 1: Arguments, and that closure becomes the entry point.
- 6:42Speaker 2: It becomes the main function for that new parallel worker instantly,
- 6:46Speaker 2: and this is portable.
- 6:47Speaker 1: Right. People shouldn't worry about whether they're on a Mac
- 6:50Speaker 1: or Linux or Windows.
- 6:51Speaker 2: Absolutely, the model is fantastic for that. The underlying system
- 6:55Speaker 2: handles all the platform specific stuff, so your concurrency logic
- 6:59Speaker 2: stays the same.
- 6:59Speaker 1: Ever, now, when you call thread dot spawn, you don't
- 7:02Speaker 1: just like fire and forget. It gives you something back.
- 7:05Speaker 2: It does. It returns a really crucial object called a
- 7:07Speaker 2: join handle. This handle is your lifeline to that spawn thread, and.
- 7:11Speaker 1: The most common thing you do with it is called join.
- 7:13Speaker 2: Right, if you call join in your main thread, you're
- 7:16Speaker 2: basically saying, okay, pause right here, wait until that other
- 7:19Speaker 2: thread has finished all of its work and exited completely.
- 7:23Speaker 1: Well, what's cool is how the result gets packaged.
- 7:25Speaker 2: Yes, the join method returns a wrapper usually called a result.
- 7:30Speaker 2: Inside that result, you'll either find the successful value that
- 7:33Speaker 2: the thread returned, or you'll find an.
- 7:36Speaker 1: Error specifically if the thread crashed.
- 7:39Speaker 2: If it panic commit execution exactly, so you have to
- 7:41Speaker 2: handle that result safely to get your data back.
- 7:43Speaker 1: So threads, give us true concurrency using multiple cores at once.
- 7:49Speaker 1: But we absolutely have to talk about the costs. Threads
- 7:52Speaker 1: are heavyweight.
- 7:53Speaker 2: They really are, and it's something we often forget. Spawning
- 7:56Speaker 2: a new operating system thread is an expensive operation. For
- 7:59Speaker 2: every single thread, the OS has to set aside a
- 8:02Speaker 2: dedicated chunk of memory for its stack. We're talking two
- 8:06Speaker 2: to four megabytes of rams, sometimes.
- 8:08Speaker 1: More, and if you launch hundreds of them.
- 8:10Speaker 2: That memory overhead adds up incredibly fast. It can become unsustainable.
- 8:13Speaker 1: And that's just the memory. There's also the runtime cost
- 8:16Speaker 1: context switching hmm.
- 8:18Speaker 2: The CPU can only do one thing per core at
- 8:20Speaker 2: a time, so if you have say eight threads running
- 8:24Speaker 2: on a quad core machine, the CPU is constantly having
- 8:26Speaker 2: to save the state of thread A, load the state
- 8:29Speaker 2: of thread B, run it for a few milliseconds, save it,
- 8:32Speaker 2: load the next.
- 8:33Speaker 1: One, and that process of saving and loading.
- 8:35Speaker 2: That's context switching. It's pure cpu overhead. It's time the
- 8:39Speaker 2: system spends managing work instead of doing work. Too many
- 8:43Speaker 2: threads and your performance just falls off a cliff.
- 8:45Speaker 1: This is why it's so important to know when to
- 8:47Speaker 1: use a thread. If your code is CPU bound doing
- 8:50Speaker 1: heavy math, for instance, threads.
- 8:52Speaker 2: Are perfect the best tool for the job.
- 8:54Speaker 1: But if your thread is just going to be waiting
- 8:55Speaker 1: around waiting for a file from the disc or for
- 8:58Speaker 1: a network response, that's iobound and threads are total overkill
- 9:03Speaker 1: for that.
- 9:03Speaker 2: And that's exactly why the world moved towards a single weight.
- 9:06Speaker 2: Unlike OS threads, acinkle weight lets you manage thousands of
- 9:09Speaker 2: concurrent tasks on just a handful of actual threads. It
- 9:12Speaker 2: avoids all that heavyweight memory allocation and the context switching costs.
- 9:16Speaker 1: Because the tasks cooperate instead of being forced to stop
- 9:19Speaker 1: and start by the OS, they.
- 9:21Speaker 2: Yield control when they hit an ioweight. It's a much
- 9:23Speaker 2: more efficient model for IO.
- 9:25Speaker 1: Okay, so we reserve threads for the intense calculations, and
- 9:29Speaker 1: we use that move closure to get the data there safely.
- 9:32Speaker 2: That combination is non negotiable when you call thread dot spawn.
- 9:36Speaker 2: If your closure needs outside data like a big vector,
- 9:40Speaker 2: that closure must be marked with move. It has to
- 9:43Speaker 2: take the data by value. The compiler just can't make
- 9:46Speaker 2: the safety guarantees otherwise.
- 9:48Speaker 1: Let's walk through a quick thought experiment to see what
- 9:50Speaker 1: true interleaving looks like. Okay, imagine we spawn a child
- 9:54Speaker 1: thread to do something expensive. Let's say it has a
- 9:57Speaker 1: five hundred millisecond pause right at the start. Then it
- 10:00Speaker 1: does a heavy calculation.
- 10:02Speaker 2: And meanwhile the main thread is busy doing its own thing.
- 10:05Speaker 2: Maybe it's printing letters to the screen A, B, C,
- 10:08Speaker 2: and so on with a two hundred millisecond pause between
- 10:11Speaker 2: each one.
- 10:11Speaker 1: Right, So when you run this, which you see is fascinating,
- 10:14Speaker 1: the main thread prints A and the princes B, but
- 10:17Speaker 1: before it can print C, that five hundred millisecond delay
- 10:20Speaker 1: on the child thread is over as calculation finishes and
- 10:22Speaker 1: it's a result gets printed right.
- 10:23Speaker 2: In the middle, and then the main thread picks back up.
- 10:25Speaker 1: Then you see C, D, E, and F. That interleaving
- 10:30Speaker 1: is proof that both threads were genuinely running at the
- 10:32Speaker 1: same time, sharing the CPU.
- 10:35Speaker 2: So once you have all these threads running, the next
- 10:37Speaker 2: big challenge is communication. How do you get them to
- 10:39Speaker 2: talk to each other without corrupting data or creating race conditions.
- 10:44Speaker 1: And that's where channels come in.
- 10:45Speaker 2: The classic pattern. Channels are the standard safe way to
- 10:49Speaker 2: pass messages between threads. You create one and you get
- 10:53Speaker 2: a pair of tools.
- 10:53Speaker 1: Back, a transmitting side TX and a receiving side RX.
- 10:57Speaker 2: Exactly one thread uses the TA to send a message,
- 11:01Speaker 2: another thread uses the RX to receive it. It's like
- 11:04Speaker 2: a queue and it prevents conflicts because only the receiver
- 11:07Speaker 2: ever owns the data after it's been sent.
- 11:09Speaker 1: And we often hear about unbounded channels, what does that mean?
- 11:12Speaker 2: In practice, unbounded just means the sending thread doesn't have
- 11:15Speaker 2: to wait. It can just keep sending messages and the
- 11:18Speaker 2: channel will buffer them until you run out of memory.
- 11:20Speaker 2: And the really useful part is that you can clone
- 11:22Speaker 2: the transmitting side.
- 11:23Speaker 1: Ah, so you can have many senders.
- 11:26Speaker 2: You can have dozens of threads, each with its own
- 11:28Speaker 2: TX handle all sending messages to one single central RX receiver.
- 11:34Speaker 2: It's a very common and powerful pattern.
- 11:36Speaker 1: Let's look at one last timing example to see how
- 11:39Speaker 1: this gives you explicit control. Let's spawn two threads again,
- 11:42Speaker 1: A and B both are going to send two messages each.
- 11:46Speaker 1: So A one and A two and B one and
- 11:47Speaker 1: B two back to the main receiver.
- 11:49Speaker 2: Okay, And if both threads start with no pause, they
- 11:52Speaker 2: just race to the channel. The output is well nondeterministic.
- 11:55Speaker 2: You might get A one, B one, A two, B two,
- 11:58Speaker 2: or some other mix. It just depends on the CPU
- 12:00Speaker 2: scheduler at that moment.
- 12:01Speaker 1: But now let's change it. Let's add a five hundred
- 12:03Speaker 1: millisecond pause to the very beginning of thread A, but
- 12:06Speaker 1: let thread B start immediately.
- 12:08Speaker 2: Now the output becomes completely deterministic. The order reverses. Thread
- 12:12Speaker 2: B gets that huge headstart, sends both B one and
- 12:14Speaker 2: B two, and only then does thread A finally wake
- 12:17Speaker 2: up and send A one and A two.
- 12:18Speaker 1: So, by controlling the timing inside those initial move closures,
- 12:22Speaker 1: you are directly controlling the synchronization of the whole program.
- 12:24Speaker 2: You have explicit control.
- 12:26Speaker 1: Yes, So when the main thread is in that loop
- 12:29Speaker 1: just waiting for messages from the receiver, how does it
- 12:32Speaker 1: know when to stop? When is it all over?
- 12:34Speaker 2: That's a great point of sort of good hygiene. The
- 12:37Speaker 2: receiving loop on a channel will automatically and gracefully exit
- 12:40Speaker 2: when two things are true. First, all the transmitting sides
- 12:43Speaker 2: have been dropped or closed okay, And second, the channel's
- 12:46Speaker 2: internal buffer is empty. But and this is important, even
- 12:50Speaker 2: after that loop exits, it's still best practice to call
- 12:53Speaker 2: join on all your thread handles. It just ensures a
- 12:56Speaker 2: clean shut down and lets you check if any of
- 12:58Speaker 2: your workers crash.
- 12:59Speaker 1: I feel like a really good place to wrap up
- 13:01Speaker 1: our deep dive into the architecture of modern concurring code.
- 13:04Speaker 2: I think so to quickly summarize, closures give you this
- 13:08Speaker 2: incredible power for functional pipelines your map filter full, and
- 13:12Speaker 2: they are the key to safely getting data into threads
- 13:14Speaker 2: with the move keyword.
- 13:16Speaker 1: And threads give you true parallelism managed with joint handles
- 13:20Speaker 1: and safe communication with channels.
- 13:21Speaker 2: That's the whole picture.
- 13:23Speaker 1: So this brings us to an important question for you
- 13:25Speaker 1: the listener, to think about. We just saw how easy
- 13:28Speaker 1: it is for multiple child threads to send data back
- 13:32Speaker 1: to a single receiver in the main thread. But how
- 13:34Speaker 1: would you design the system to reverse that flow? How
- 13:38Speaker 1: would you let the main thread send instructions to multiple
- 13:42Speaker 1: running child threads all at the same time.
- 13:44Speaker 2: That's a really good puzzle, and it goes beyond a
- 13:46Speaker 2: simple channel. A little hint for you. Since you'd need
- 13:49Speaker 2: the child threads to share the receiving end of a channel,
- 13:52Speaker 2: you'll need to look into things like atomic reference counting
- 13:55Speaker 2: combined with a mutual exclusion lock. Those ARC and utex
- 13:58Speaker 2: patterns are the key to unl unlocking that next level
- 14:01Speaker 2: of concurrent control.