线程中对象的借用和所有权

4

非常抱歉,这是一个新手问题。错误在这里:

<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);
}
1个回答

5

Arc不允许改变其内部状态,即使容器被标记为可变。你应该使用其中之一:CellRefCellMutexCellRefCell都不是线程安全的,因此你应该使用Mutex文档中的最后一段)。

示例:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接