Легка одиниця паралельного виконання. На OS-рівні.
use std::thread;
use std::time::Duration;
let handle = thread::spawn(|| {
for i in 1..5 {
println!("Thread: {}", i);
thread::sleep(Duration::from_millis(100));
}
});
handle.join().unwrap(); // Чекаємо завершення
Безпечна передача даних між потоками через channels (як Go).
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("hello").unwrap();
});
let msg = rx.recv().unwrap();
println!("Received: {}", msg);
Mutual exclusion - синхронізація доступу до спільних даних.
use std::sync::Mutex;
use std::sync::Arc;
use std::thread;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Counter: {}", *counter.lock().unwrap());
Atomic Reference Counting. Дозволяє кільком потокам мати власність.
Лекція 21: Docker и Контейнери
Дякую за увагу! 💾