Siddharth Teli
Siddharth Teli

Reputation: 117

Handling locks for multi thread ds in rust

I have a complex nested struct which should handle high read/write via multi threads. MRE:

use std::sync::RwLock;
use std::sync::atomic::AtomicBool;
use once_cell::sync::OnceCell;

#[derive(Default)]
struct Alien {
    info: Info,
    evil: AtomicBool,
}

#[derive(Default)]
struct Info {
    address: String,
}

fn get_alien_instance() -> &'static Alien {
    let alien = Alien::default();
    static INSTANCE: OnceCell<Alien> = OnceCell::new();
    INSTANCE.get_or_init(move || alien)
}

Alien is the parent struct with multiple fields and nested structs.Will use &'static Alien and interior mutability to mut fields of Alien. I am moving into issues with nested locks and mutability. I want to use single (non nested) lock for Info struct but handle its mutation inside its impl block.

A weird solution would be mutating Info fields inside Alien impl itself. Something like this -

impl Alien {
    fn update_info(&self) {
        let mut info = self.info.write().unwrap();
        info.address = "HEllo".to_string();
    }
}

Other way would be wrapping everything with Rwlock.

#[derive(Default)]
struct Alien {
    info: RwLock<Info>,
    evil: AtomicBool,
}

#[derive(Default)]
struct Info {
    address: RwLock<String>,
}

impl Info {
    fn update_address(&self) {
        let mut address = self.address.write().unwrap();
        *address = String::from("Mars");
    }
}

One more approach would be passing RwLockWriteGuard to Info impl. I am not sure how to deal with this. What would be an ideal solution while managing high read/write?

Upvotes: 0

Views: 52

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299800

What is the narrow scope of atomicity you need?

When considering lock, a very important question is to ask yourself about the narrowest possible scope of atomicity.

It's typically a bit easier to reason about negatively, by asking yourself the question: is it fine if X and Y are NOT changed atomically?

For example, consider your Info struct, inflated for the sake of this example:

struct Info {
    name: String,
    address: String,
}

Is it fine if one thread modifies name and the other modifies address?

That is, if you execute the following:

fn update_info(info: &mut Info, name: String, address: String) {
    info.name = name;
    info.address = address;
}

On two threads in parallel, you may get:

  • T0: Update name to "Ali Baba".
  • T1: Update name to "Grand Vizir".
  • T1: Update address to "Palace".
  • T0: Update address to "Cavern".

And after that your info instance points to the Grand Vizir, living in the Cavern.

Well... that's an example of undesirable behavior, and therefore we conclude here that both name and address must be updated atomically.

The narrowest scope of atomicity is thus Info, entire.

Lock Decision

The entire scope of atomicity must then be protected by a single lock, with no interior locks. Which in my case above would mean that there should be no lock (or atomic fields) in Info itself.

Thus, the solution I would end up with is:

struct Alien {
    info: RwLock<Info>,
    evil: AtomicBool,
}

struct Info {
    name: String,
    address: String,
}

Note: there are further considerations, notably it may be simpler to have coarser grained locks (ie, less locks overall); the narrowest scope only determines how fine the locks can get while enforcing functionality, giving an upper bound on the number of locks.

Upvotes: 0

啊鹿Dizzyi
啊鹿Dizzyi

Reputation: 908

Does this help you? Here's just what I would do, I think when you have Alien.info as RwLock, you don't need t RwLock inside Info.

use std::sync::{OnceLock, RwLock};

#[derive(Default)]
struct Alien {
    info: RwLock<Info>,
}

static INSTANCE: OnceLock<Alien> = OnceLock::new();

fn get_alien_instance() -> &'static Alien {
    INSTANCE.get_or_init(move || Alien::default())
}

#[derive(Default)]
struct Info {
    address: String,
}

impl Info {
    pub fn update(&mut self, new: String) {
        self.address = new;
    }
}

fn main() {
    std::thread::spawn(|| {
        for s in ["Planet Foo", "Sun Bar", "Baz Galaxy"].iter().cycle().take(10){
            get_alien_instance()
                .info
                .write()
                .unwrap()
                .update(s.to_string());
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    });

    for _ in 0..100 {
        println!("Address: {}",get_alien_instance().info.read().unwrap().address);
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}

Upvotes: 0

Related Questions