How to change the value of a ref value

use std::sync::{Mutex, Arc};
use std::thread::sleep;
use std::time::Duration;

pub struct A {
    c: i32,
}

impl A {
    fn new() -> A {
        A {
            c: 4
        }
    }
}

pub struct M {
    a: Arc<Mutex<A>>,
}

impl M {
    fn change(&mut self) {
        self.a.get_mut().unwrap().c = 500;
    }
}

pub struct N {
    a: Arc<Mutex<A>>,
}

impl N {
    fn change(&mut self) {
        self.a.get_mut().unwrap().c = 500;
    }
}

struct B {
    m: M,
    n: N,
}

impl B {
    fn new(aa: Arc<Mutex<A>>, bb: Arc<Mutex<A>>) -> B {
        B {
            m: M { a: aa },
            n: N { a: bb },
        }
    }

    fn update(&mut self) {
        self.m.change()
    }
}


fn main() {
    let xx = Arc::new(Mutex::new(A::new()));
    let mut b = B::new(xx.clone(), xx.clone());

    loop {
        sleep(Duration::from_secs(1));
        b.update();
    }
}

How can i change the value of self.a.c in method change() ?
The above code doesn't seem to work

or could provide a better to implement it. Thanks anyway

// title is not suitable, but I don't know how to describe it.

When you have a value shared by multiple cloned Arc pointers, you cannot get an exclusive reference (&mut self) to it. Instead, you should change all your functions to take shared references (&self), and use the Mutex::lock method for mutation.

Playground

1 Like

got it thanks !!!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.