在线程上借用对象和所有权

dir*_*ine 4 rust

对不起新手问题.这里的错误是

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

我已经尝试了很多东西来解决这个问题,但我知道这是一个简单的错误.任何帮助非常感谢.

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);
}
Run Code Online (Sandbox Code Playgroud)

Hau*_*eth 5

Arc即使容器被标记为可变,也不允许改变它的内部状态.你应该使用其中之一Cell,RefCellMutex.这两个CellRefCell是非线程所以你应该使用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();
}
Run Code Online (Sandbox Code Playgroud)

围栏