rust - 线程上对象的借用和所有权

标签 rust

抱歉新手问题。这里的错误是

<anon>:30:5: 30:17 error: cannot borrow immutable borrowed content as mutable
<anon>:30     routing_node.put(3);
              ^^^^^^^^^^^^

我已经尝试了很多方法来解决这个问题,但我确信这是一个简单的错误。非常感谢任何帮助。

use std::thread;
use std::thread::spawn;
use std::sync::Arc;

struct RoutingNode {
  data: u16
}

impl RoutingNode {
  pub fn new() -> RoutingNode {
      RoutingNode { data: 0 }
}

pub fn run(&self) {
    println!("data : {}", self.data);
}

pub fn put(&mut self, increase: u16) {
    self.data += increase;
}
}

fn main() {
  let mut routing_node = Arc::new(RoutingNode::new());
  let mut my_node = routing_node.clone();
{
    spawn(move || {my_node.run(); });
}

routing_node.put(3);
}

最佳答案

Arc 不允许改变其内部状态,即使容器被标记为可变。您应该使用 CellRefCellMutex 之一。 CellRefCell 都是非线程安全的,因此您应该使用 Mutex ( last paragraph in docs )。

例子:

use std::thread::spawn;
use std::sync::Mutex;
use std::sync::Arc;

struct RoutingNode {
    data: u16,
}

impl RoutingNode {
    pub fn new() -> Self { RoutingNode { data: 0, } }  
    pub fn run(&self) { println!("data : {}" , self.data); }   
    pub fn put(&mut self, increase: u16) { self.data += increase; }
}

fn main() {
    let routing_node = Arc::new(Mutex::new(RoutingNode::new()));
    let my_node = routing_node.clone();
    let thread = spawn(move || { my_node.lock().unwrap().run(); });

    routing_node.lock().unwrap().put(3);
    let _ = thread.join();
}

Playpen

关于rust - 线程上对象的借用和所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29985655/

相关文章:

rust - 如何将 Rust 模块文档保存在单独的 Markdown 文件中?

rust - 如何为结构的可变引用中的字段换入新值?

rust - 使用 Rust 读取 .dfb 文件会引发无效字符错误

file - Rust 读取文件

rust - 如何使用structopt将不可能的值附加到结构上?

rust - 在柴油塔中使用新类型

rust - 如何为具有 "rented"引用的类型实现特征

rust - 如何让我的 Rust 程序链接到另一个 glibc?

rust - 将静态字符串传递给rust中的macro_rule

rust - 有效地获取Vec <Ref <'a, T>> from Ref<' a,BTreeSet <T >>