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?

1

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));
    }
}

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật