Важные темы Rust
Rust Channels: mpsc
Send messages from one thread to another instead of sharing memory.
Что вы узнаете
- mpsc::channel
- send and receive
- How a channel closes
Producer to main
- 1
sender.sendproducer thread - 2
channelstep 1, step 2, step 3 - 3
for message in receivermain thread
A one-way pipe between threads
A channel is a one-way pipe between threads. One side sends values and the other receives them, so threads can work together without sharing memory.
channel returns a sender and a receiver. The producer thread owns the sender and sends three messages. When the thread ends, the sender is dropped and the channel closes, which ends the for loop over the receiver.
Главное
channel()returns a sender and a receiver.- The receiver can be used in a for loop.
- Dropping the sender closes the channel.
Пример на Rust, который можно запустить
Rust
main.rs
use std::sync::mpsc;
use std::thread;
fn main() {
let (sender, receiver) = mpsc::channel();
let producer = thread::spawn(move || {
for step in 1..=3 {
sender.send(format!("step {step} done")).unwrap();
}
}); // sender is dropped here, which closes the channel
for message in receiver {
println!("received: {message}");
}
producer.join().unwrap();
println!("all messages received");
}
received: step 1 done
received: step 2 done
received: step 3 done
all messages receivedПрактика
Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.
Закончили этот урок?
Отметьте его как изученный, чтобы следить за прогрессом.
Ваш прогресс сохранён в этом браузере Войдите, чтобы он был доступен на всех устройствах.
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
Все задачи