use std::thread;
use std::sync::mpsc;
use std::process::exit;
struct Hello {
text: String
}
impl Hello {
fn world(&self){
println!("{} World", &self.text);
exit();
}
}
thread::spawn(||{
let ex: Hello = Hello {
text: "hello"
}
loop {
tx.tx();//what do i do here
}
})
thread::spawn(|| {
loop {
rx.rx() //and here
}
})
如何通过发送方发送一些内容,从而在接收方的线程中执行world
方法?
答案 0 :(得分:0)
您要执行的是进程间通信。您首先要创建线程,但是要使用MPSC(多生产者,单消费者)渠道来使他们与其他人交谈,还有一些工作要做。
希望此示例激发您的hello::world()
方法有帮助:
use std::process::exit;
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
struct Hello {
text: String,
}
impl Hello {
fn world(&self) {
println!("{} World", &self.text);
}
}
static NTHREADS: usize = 3;
fn main() {
let (tx, rx): (Sender<String>, Receiver<String>) = mpsc::channel();
for id in 0..NTHREADS {
// The sender endpoint can be copied
let thread_tx = tx.clone();
// Each thread will send its id via the channel
thread::spawn(move || {
// The thread takes ownership over `thread_tx`
// Each thread queues a message in the channel
let hello_text = format!("hello {}", id);
thread_tx.send(hello_text).unwrap();
// Sending is a non-blocking operation, the thread will continue
// immediately after sending its message
println!("thread {} finished", id);
});
}
// Here, all the messages are received and hello instance is created with the
// data received from the sender aka thread_tx.send command above. From there
// we call world() method
for _ in 0..NTHREADS {
// The `recv` method picks a message from the channel
// `recv` will block the current thread if there no messages available
let text = rx.recv().unwrap();
let hello = Hello {
text: text.to_string(),
};
hello.world();
}
}
该代码已修改from this example。