【问题标题】:How to create a global mutable bool status flag如何创建全局可变布尔状态标志
【发布时间】:2015-04-08 17:01:52
【问题描述】:

前言:我已经完成了我的研究,并且知道这确实不是一个好主意/拥有一个 Rust 也不是惯用的。完全愿意接受其他解决此问题的方法的建议。

背景:我有一个连接到 websocket 的控制台应用程序,一旦连接成功,服务器就会发送“已连接”消息。我有发送者,接收者是单独的线程,一切都很好。在connect() 调用之后,一个循环开始并在终端中放置一个提示,表明应用程序已准备好接收来自用户的输入。

问题:问题是当前执行流程调用connect,然后立即显示提示,然后应用程序收到来自服务器的消息说明它已连接。

我将如何用高级语言解决这个问题:放置一个全局布尔值(我们称之为ready),一旦应用程序“准备好”,然后显示提示。

我认为这在 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() 闭包中借用不可变对象的主要问题。

【问题讨论】:

  • 虽然我鼓励您使用全局可变状态,但如果我没有至少指向 this answer 向您展示如何做到这一点。

标签: global-variables rust


【解决方案1】:

听起来您确实希望有两个线程通过 channels 进行通信。看看这个例子:

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 个线程在起作用:

  1. 主线程。
  2. 从“套接字”读取的线程。
  3. 与用户交互的线程。

这些线程中的每一个都可以保持它自己的非共享状态。这使得推理每个线程变得更容易。线程使用channel 在它们之间安全地发送更新。跨线程的数据被封装在一个枚举中。

当我运行它时,我得到了

socket: started!
console: started!
socket: connected!
console: I'm connected!
socket: disconnected!
socket: closed!
console: I'm disconnected!

【讨论】:

  • 是的,这很有意义。再一次非常感谢你)。这是一种更简洁、更简洁的方法。正如我读到的所有内容所述,通常有比使用全局更好的方法,我只是想不出一个。
猜你喜欢
  • 1970-01-01
  • 2021-11-23
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 2013-12-21
  • 2014-11-29
相关资源
最近更新 更多