前言:我已经完成了我的研究,并且知道这不是一个好主意/也不是惯用的Rust有一个。完全接受有关解决此问题的其他方法的建议。
后台:我有一个连接到websocket的控制台应用程序,一旦连接成功,服务器就会发送“已连接”消息。我有发送者,接收者是单独的线程,一切都很好。在connect()
调用之后,循环开始并在终端中发出提示,表示应用程序已准备好接收来自用户的输入。
问题:问题是当前的执行流程连接,然后立即显示提示,然后应用程序从服务器收到消息,说明它已连接。
我如何用更高级别的语言解决这个问题:放置一个全局bool(我们称之为ready
),一旦应用程序“准备就绪”,然后显示提示符。< / p>
我认为这可能会在Rust中看到:
//Possible global ready flag with 3 states (true, false, None)
let ready: Option<&mut bool> = None;
fn main(){
welcome_message(); //Displays a "Connecting..." message to the user
//These are special callback I created and basically when the
//message is received the `connected` is called.
//If there was an error getting the message (service is down)
//then `not_connected` is called. *This is working code*
let p = mylib::Promise::new(connected, not_connected);
//Call connect and start websocket send and receive threads
mylib::connect(p);
//Loop for user input
loop {
match ready {
Some(x) => {
if x == true { //If ready is true, display the prompt
match prompt_input() {
true => {},
false => break,
}
} else {
return; //If ready is false, quit the program
}
},
None => {} //Ready is None, so continue waiting
}
}
}
fn connected() -> &mut bool{
println!("Connected to Service! Please enter a command. (hint: help)\n\n");
true
}
fn not_connected() -> &mut bool{
println!("Connection to Service failed :(");
false
}
问题: 你会如何在Rust中解决这个问题?我已经尝试将它传递给所有库方法调用,但遇到了一些关于在FnOnce()闭包中借用不可变对象的主要问题。
答案 0 :(得分:3)
听起来你想要有两个通过频道进行通信的线程。看看这个例子:
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
enum ConsoleEvent {
Connected,
Disconnected,
}
fn main() {
let (console_tx, console_rx) = mpsc::channel();
let socket = thread::spawn(move || {
println!("socket: started!");
// pretend we are taking time to connect
thread::sleep(Duration::from_millis(300));
println!("socket: connected!");
console_tx.send(ConsoleEvent::Connected).unwrap();
// pretend we are taking time to transfer
thread::sleep(Duration::from_millis(300));
println!("socket: disconnected!");
console_tx.send(ConsoleEvent::Disconnected).unwrap();
println!("socket: closed!");
});
let console = thread::spawn(move || {
println!("console: started!");
for msg in console_rx.iter() {
match msg {
ConsoleEvent::Connected => println!("console: I'm connected!"),
ConsoleEvent::Disconnected => {
println!("console: I'm disconnected!");
break;
}
}
}
});
socket.join().expect("Unable to join socket thread");
console.join().expect("Unable to join console thread");
}
这里有3个主题在线:
这些线程中的每一个都可以维护自己的非共享状态。这允许推理每个线程更容易。线程使用channel
安全地在它们之间发送更新。穿过线程的数据封装在枚举中。
当我运行时,我得到了
socket: started!
console: started!
socket: connected!
console: I'm connected!
socket: disconnected!
socket: closed!
console: I'm disconnected!