Skip to content
เข้าสู่ระบบ

Channel Enums

Channel-related enums สำหรับ inter-thread communication ใน Rust รวมถึง error types สำหรับ send และ receive operations

Error type สำหรับ non-blocking receive operations

use std::sync::mpsc::{channel, TryRecvError};
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = channel();
// TryRecvError::Empty - channel empty but senders exist
match rx.try_recv() {
Ok(msg) => println!("Got: {}", msg),
Err(TryRecvError::Empty) => println!("Channel empty, sender alive"),
Err(TryRecvError::Disconnected) => println!("Sender gone"),
}
// Spawn sender
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(100));
tx.send("Hello").unwrap();
});
// Polling pattern
loop {
match rx.try_recv() {
Ok(msg) => {
println!("Received: {}", msg);
break;
}
Err(TryRecvError::Empty) => {
println!("Waiting...");
thread::sleep(Duration::from_millis(50));
}
Err(TryRecvError::Disconnected) => {
println!("Sender disconnected");
break;
}
}
}
handle.join().unwrap();
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด