Rust's ownership system enables "fearless concurrency" - the ability to write concurrent code with confidence that the compiler will catch data races before they happen. This chapter covers threads, message passing, shared state, and the traits that make it all work.
In most languages, concurrent programming is notoriously error-prone. Data races are subtle bugs that only appear under specific timing conditions, making them nearly impossible to reproduce and debug. Rust prevents data races at compile time - if your concurrent code compiles, it's free from data races. This is a game-changer for systems programming.
Spawn threads using thread::spawn, which takes a closure that runs in the new thread:
use std::thread;
use std::time::Duration;
fn main() {
// Spawn a new thread
let handle = thread::spawn(|| {
for i in 1..10 {
println!("spawned thread: {}", i);
thread::sleep(Duration::from_millis(1));
}
});
// Main thread continues
for i in 1..5 {
println!("main thread: {}", i);
thread::sleep(Duration::from_millis(1));
}
// Wait for spawned thread to finish
handle.join().unwrap();
println!("All threads completed!");
}
thread::spawn returns a JoinHandle. Calling .join() on it blocks the current thread until the spawned thread completes. The return value is a Result - if the thread panicked, you'll get an Err.
Use the move keyword to transfer ownership of captured variables to the thread:
use std::thread;
fn main() {
let v = vec![1, 2, 3];
// move transfers ownership of v to the thread
let handle = thread::spawn(move || {
println!("vector: {:?}", v);
});
// println!("{:?}", v); // ERROR: v was moved to the thread
handle.join().unwrap();
}
Rust can't know how long the spawned thread will run. If it borrowed v, the main thread might drop v before the spawned thread finishes, creating a dangling reference. move ensures the thread owns its data, eliminating this possibility.
use std::thread;
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
// Clone data for each thread
let numbers_clone = numbers.clone();
let handle = thread::spawn(move || {
let sum: i32 = numbers_clone.iter().sum();
println!("Sum in thread: {}", sum);
});
println!("Original: {:?}", numbers); // Still available
handle.join().unwrap();
}
Channels provide safe communication between threads following the motto: "Do not communicate by sharing memory; instead, share memory by communicating."
use std::sync::mpsc; // multiple producer, single consumer
use std::thread;
fn main() {
// Create a channel
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let msg = String::from("hello from thread");
tx.send(msg).unwrap();
// println!("{}", msg); // ERROR: msg was moved into channel
});
// Receive blocks until a message is available
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let messages = vec![
String::from("hello"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for msg in messages {
tx.send(msg).unwrap();
thread::sleep(Duration::from_millis(200));
}
});
// Iterate over received messages
for received in rx {
println!("Got: {}", received);
}
}
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let tx2 = tx.clone(); // Clone the sender
thread::spawn(move || {
tx.send(String::from("from tx1")).unwrap();
});
thread::spawn(move || {
tx2.send(String::from("from tx2")).unwrap();
});
// Receive from both producers
for received in rx {
println!("Got: {}", received);
}
}
| Method | Behavior |
|---|---|
rx.recv() |
Blocks until a message is received or channel closes |
rx.try_recv() |
Returns immediately with Result (non-blocking) |
rx.recv_timeout(duration) |
Blocks for specified duration, then returns error |
tx.send(value) |
Sends value, returns error if receiver dropped |
Mutex (mutual exclusion) provides safe access to shared data - only one thread at a time can access the data:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
// Acquire lock - blocks until available
let mut num = m.lock().unwrap();
*num = 6;
} // Lock released here when MutexGuard goes out of scope
println!("m = {:?}", m); // Mutex { data: 6, ... }
}
If you acquire a lock and never release it (or try to lock it again from the same thread), your program will deadlock. The lock is automatically released when the MutexGuard goes out of scope, so keeping critical sections small is important.
Arc (Atomic Reference Counting) allows multiple threads to own shared data. It's the thread-safe version of Rc:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Arc allows multiple owners across threads
// Mutex allows mutation by one thread at a time
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter); // Clone the Arc
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
// Wait for all threads
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap()); // 10
}
Rc<T>: Single-threaded reference counting (faster, no atomic operations)Arc<T>: Thread-safe atomic reference counting (for multi-threaded code)The compiler won't let you use Rc across threads - you'll get a compile error telling you to use Arc.
Two marker traits govern thread safety in Rust:
| Trait | Meaning | Example Types |
|---|---|---|
Send |
Type can be transferred between threads | Most types: String, Vec, i32 |
Sync |
Type can be referenced from multiple threads | Immutable references, Mutex<T> |
// Types that are NOT Send or Sync // Rc is NOT Send - use Arc instead // RefCell is NOT Sync - use Mutex instead // Raw pointers are neither // If all components of a type are Send, the type is Send // If all components of a type are Sync, the type is Sync
You rarely implement these traits manually. The compiler automatically derives them based on a type's contents. If you try to send a non-Send type to another thread, you'll get a clear compile error explaining the issue.
Rust also supports async programming for I/O-bound tasks. While threads are great for CPU-bound parallel work, async is more efficient for handling many concurrent I/O operations:
// Requires an async runtime like tokio
use tokio;
#[tokio::main]
async fn main() {
let result = fetch_data().await;
println!("{}", result);
// Run multiple futures concurrently
let (r1, r2) = tokio::join!(
fetch_data(),
fetch_data()
);
}
async fn fetch_data() -> String {
// Simulate async I/O operation
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
"data".to_string()
}
Async is a large topic that deserves its own deep dive. This is just a preview of what's possible.
thread::spawn with move closures to transfer ownership to new threadsmpsc - multiple producers, single consumer; ownership is transferred through the channelmove keyword often required when spawning threads? What would happen without it?mpsc stand for? How do you create multiple producers for a channel?Arc<Mutex<T>> instead of just Mutex<T> for shared state across threads?Send and Sync traits? Why is Rc not Send?Apply everything you've learned to build practical applications:
Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.
Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.