advance/concurrency-with-threads/message-passing #1067
Replies: 10 comments 20 replies
-
在文章的 线程是如何结束的 章节,有这么一个例子: use std::thread;
use std::time::Duration;
fn main() {
// 创建一个线程A
let new_thread = thread::spawn(move || {
// 再创建一个线程B
thread::spawn(move || {
loop {
println!("I am a new thread.");
}
})
});
// 等待新创建的线程执行完成
new_thread.join().unwrap();
println!("Child thread is finish!");
// 睡眠一段时间,看子线程创建的子线程是否还在运行
thread::sleep(Duration::from_millis(100));
} 想问一下这里如果新创建的线程一直没有结束,那主线程是不是也会一直等,而不是文章中说的会执行到 |
Beta Was this translation helpful? Give feedback.
-
借用ss会在s之前释放,但编译器会报错怎么办 fn main() {
let s = "1212".to_string();
let ss = &s;
let handle = thread::spawn(move || {
println!("{}", ss);
});
handle.join().unwrap();
} |
Beta Was this translation helpful? Give feedback.
-
妈的那个新手容易遇到的坑那里恰好困扰了我两天 |
Beta Was this translation helpful? Give feedback.
-
crossbeam-channel官方文档的翻译:https://doraemon.xlog.app/crossbeam_channelmd |
Beta Was this translation helpful? Give feedback.
-
这里感觉很奇怪,那下面代码里 不论是tx还是tx1,都只有在main结束之后 才会被drop? 那岂不是跳不出for循环?
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
tx.send(String::from("hi from raw tx")).unwrap();
});
thread::spawn(move || {
tx1.send(String::from("hi from cloned tx")).unwrap();
});
for received in rx {
println!("Got: {}", received);
}
} |
Beta Was this translation helpful? Give feedback.
-
讲的太好了 第一次看到这么高质量的rust的文章 |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
请问一下,对于文章中的这段代码
它tx每次发送之后都会休眠一秒,作为迭代器接收tx传递数据的rx,为什么能够自动等待到tx发送完全才脱离for循环,而不是接到一个循环一遍之后就直接跳出循环了呢? |
Beta Was this translation helpful? Give feedback.
-
发送者全部drop或接收者被drop |
Beta Was this translation helpful? Give feedback.
-
看本地标准库代码时,发现std::sync::mpsc实际上是封装了mpmc #[stable(feature = "rust1", since = "1.0.0")]
pub struct Sender<T> {
inner: mpmc::Sender<T>,
} 点开mpmc的实现会发现: // This module is not currently exposed publicly, but is used 这里表明,标准库里的mpmc是从crossbeam中抄过来的,只不过不对外开放 |
Beta Was this translation helpful? Give feedback.
-
advance/concurrency-with-threads/message-passing
https://course.rs/advance/concurrency-with-threads/message-passing.html
Beta Was this translation helpful? Give feedback.
All reactions