0

Let's say I have a mutable structure (i32 in the example code for simplicity) which should be shared between threads. I can use Mutex for it (and Arc for memory management). But I want to have RAII wrapper for data lock to make some specific interface of data modification, track unlocks etc.

Here the draft (I don't know which lifetime specify for MutexGuard):

use std::sync::{Arc, Mutex, MutexGuard};

pub struct SharedData {
    data: Arc<Mutex<i32>>
}

impl SharedData {
    pub fn new(value: i32) -> Self {
        SharedData {
            data: Arc::new(Mutex::new(value))
        }
    }

    pub fn lock(&self) -> LockedSharedData<'_> {
        LockedSharedData::new(self.data.clone())
    }
}

pub struct LockedSharedData<'a> {
    _data: Arc<Mutex<i32>>,
    guard: MutexGuard<'a, i32>
}

impl<'a> LockedSharedData<'a> {
    fn new(data: Arc<Mutex<i32>>) -> Self {
        LockedSharedData {
            guard: data.lock().unwrap(),
            _data: data
        }
    }

    pub fn get(&self) -> i32 {
        *self.guard
    }

    pub fn inc(&mut self) {
        *self.guard += 1;
    }
}

It predictable doesn't compile - https://rust.godbolt.org/z/4rEe3fWxK.

How to fix this pattern implementation?

kiv_apple
  • 491
  • 3
  • 13
  • 1
    Why do you want to do this? There are *many* problems in your code and I think they all come from you trying to bend over backwards instead of doing something simpler. – Aleksander Krauze Oct 17 '22 at 19:37
  • 2
    Why do you need to store the mutex alongside the guard? Otherwise, this is a duplicate of [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct) – Chayim Friedman Oct 17 '22 at 19:38
  • I added `_data` field to the struct to hold reference to `Arc` and avoid memory free while the mutex is locked. This field can be removed, actually I need only `MutexGuard` (and access to the data via it) in `LockedSharedData`. – kiv_apple Oct 17 '22 at 19:47
  • `MutexGuard` borrows from `Mutex` and therefore from `Arc`, so data will never be dropped while the guard is alive. – Cerberus Oct 18 '22 at 02:01

0 Answers0