0
0
Rustprogramming~10 mins

Concurrency safety guarantees 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 declare a thread-safe shared variable using Rust's atomic type.

Rust
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

let counter = AtomicUsize::new([1]);
Drag options to blanks, or click blank then click option'
Atrue
B"0"
C0
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string or boolean instead of a number for initialization.
2fill in blank
medium

Complete the code to spawn a thread that safely increments the atomic counter.

Rust
use std::sync::Arc;
use std::thread;

let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = Arc::clone(&counter);

let handle = thread::spawn(move || {
    counter_clone.[1](1, Ordering::SeqCst);
});
Drag options to blanks, or click blank then click option'
Afetch_add
Bload
Cstore
Dswap
Attempts:
3 left
💡 Hint
Common Mistakes
Using load or store which do not perform atomic addition.
3fill in blank
hard

Fix the error in the code to safely share a mutable vector across threads using a Mutex.

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

let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let data_clone = Arc::clone(&data);

let handle = thread::spawn(move || {
    let mut vec = data_clone.[1]().unwrap();
    vec.push(4);
});
Drag options to blanks, or click blank then click option'
Aunwrap
Bfetch_add
Cclone
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using unwrap() directly on the Arc or Mutex without locking.
4fill in blank
hard

Fill both blanks to create a thread-safe counter using Arc and Mutex.

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

let counter = Arc::new(Mutex::new([1]));
let counter_clone = Arc::clone(&counter);

let handle = thread::spawn(move || {
    let mut num = counter_clone.[2]().unwrap();
    *num += 1;
});
Drag options to blanks, or click blank then click option'
A0
Block
C1
Dclone
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing with 1 or forgetting to lock the Mutex.
5fill in blank
hard

Fill all three blanks to create a thread-safe HashMap shared across threads with Arc and Mutex.

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

let map = Arc::new(Mutex::new(HashMap::new()));
let map_clone = Arc::clone(&map);

let handle = thread::spawn(move || {
    let mut data = map_clone.[1]().unwrap();
    data.insert([2], [3]);
});
Drag options to blanks, or click blank then click option'
Alock
B"key"
C42
Dclone
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to lock the Mutex or using incorrect key/value types.