1. 52
    Rustlings arc1: Using Arc to share data safely among threads
    1m 44s

Rustlings arc1: Using Arc to share data safely among threads

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

README for this exercise.

Chris Biscardi: [0:00] Arc1 presents us with a couple of use statements that include threads and something called Arc. Arc represents a thread-safe reference-counting pointer, and Arc stands for Atomically Reference Counted. You may know of this idea from old iOS Objective-C code or something like that.

[0:19] What Arc does is provides shared ownership of a value allocated in the heap. Invoking clone on Arc gives you a new Arc instance, which points to the same allocation on the heap as the original source Arc. What Arc will do is then increase the reference count, and it will not drop the value inside of the Arc until the last reference has dropped.

[0:41] In this code, what we need to do is set a value for shared_numbers and then also create an initial binding for child_numbers such that we can use the value inside of the multiple threads that are spawned for the range zero to eight. Note that numbers here is a Vec which we've told the Rust compiler to infer the type of with this <_>, and also told that the type by using a range of to 100 as u32.

[1:06] For shared_numbers, what we'll do is create a new Arc. Note that we also need to use new binding for child_numbers. We have a number of places we could put it, including right below shared_numbers or inside of this loop.

[1:19] We're going to do this inside of the loop so that we create a new clone and increase the Arc reference counter for every offset that we spawn a new thread for.

[1:27] Note that shared_numbers is a new Arc that contains the Vec for each offset in the range zero to eight, which we spawn a thread for child_numbers, clones shared_numbers, which increments the Arc counter and allows child_numbers to access the same data