0
0
Rustprogramming~10 mins

Shared state overview in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new shared state using Arc.

Rust
use std::sync::[1];

let counter = [1]::new(0);
Drag options to blanks, or click blank then click option'
AArc
BMutex
CRwLock
DCell
Attempts:
3 left
💡 Hint
Common Mistakes
Using Mutex instead of Arc for shared ownership.
Using Cell which is not thread-safe.
2fill in blank
medium

Complete the code to lock the Mutex and get mutable access to the data.

Rust
use std::sync::{Arc, Mutex};

let counter = Arc::new(Mutex::new(0));

let mut num = counter.[1]().unwrap();
Drag options to blanks, or click blank then click option'
Aget
Bclone
Clock
Dunwrap
Attempts:
3 left
💡 Hint
Common Mistakes
Using clone instead of lock to access data.
Trying to get data without locking the Mutex.
3fill in blank
hard

Fix the error in the code to share a counter safely between threads.

Rust
use std::sync::{Arc, Mutex};
use std::thread;

let counter = Arc::new(Mutex::new(0));

let counter2 = [1].clone();

thread::spawn(move || {
    let mut num = counter2.lock().unwrap();
    *num += 1;
});
Drag options to blanks, or click blank then click option'
Acounter
Bcounter2
CMutex
DArc
Attempts:
3 left
💡 Hint
Common Mistakes
Cloning the thread-local variable instead of the Arc.
Trying to clone the Mutex instead of the Arc.
4fill in blank
hard

Fill both blanks to create a thread-safe shared counter and increment it.

Rust
use std::sync::[1];
use std::thread;

let counter = [1]::new([2]::new(0));

let counter2 = counter.clone();
Drag options to blanks, or click blank then click option'
AArc
BMutex
CCell
DRefCell
Attempts:
3 left
💡 Hint
Common Mistakes
Using Cell or RefCell which are not thread-safe.
Not wrapping Mutex inside Arc for sharing.
5fill in blank
hard

Fill all three blanks to safely share and update a counter in multiple threads.

Rust
use std::sync::[1];
use std::thread;

let counter = [1]::new([2]::new(0));

let handles: Vec<_> = (0..5).map(|_| {
    let counter = counter.clone();
    thread::spawn(move || {
        let mut num = counter.[3]().unwrap();
        *num += 1;
    })
}).collect();
Drag options to blanks, or click blank then click option'
AArc
BMutex
Clock
Dclone
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to clone the Arc before moving into the thread.
Trying to access Mutex data without locking.