Module lock

Module lock 

Source
Expand description

Safe lock utilities for concurrent programming Copyright © 2025-2026 Wenze Wei. All Rights Reserved.

This file is part of DMSC. The DMSC project belongs to the Dunimd Team.

Licensed under the Apache License, Version 2.0 (the “License”); You may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

§Safe Lock Utilities

This module provides safe abstractions for lock acquisition and management, eliminating the need for .unwrap() and .expect() calls when working with synchronization primitives. These utilities ensure robust error handling in concurrent scenarios without risking thread panics.

§Key Components

  • DMSCLockError: Specialized error type for lock-related failures
  • DMSCLockResult: Result type alias for lock operations
  • RwLockExtensions: Extension traits for standard RwLock types
  • MutexExtensions: Extension traits for standard Mutex types

§Design Principles

  1. Never Panic: All lock operations return Result instead of panicking
  2. Poison Error Handling: Properly handles poisoned locks without panicking
  3. Consistent API: Uniform error handling across all lock types
  4. Zero-Cost Abstraction: Extension traits add no overhead when unused

§Usage

use std::sync::Arc;
use dmsc::core::lock::{RwLockExtensions, DMSCLockResult};

struct SharedState {
    counter: u64,
}

impl SharedState {
    fn increment(&mut self) {
        self.counter += 1;
    }

    fn get_value(&self) -> u64 {
        self.counter
    }
}

fn example() -> DMSCLockResult<()> {
    let state = Arc::new(RwLock::new(SharedState { counter: 0 }));

    // Write lock with error handling
    {
        let mut guard = state.write_safe()?;
        guard.increment();
    }

    // Read lock with error handling
    {
        let guard = state.read_safe()?;
        assert_eq!(guard.get_value(), 1);
    }

    Ok(())
}

Structs§

DMSCLockError
Specialized error type for lock-related failures.

Traits§

MutexExtensions
Extension trait providing safe lock acquisition for Mutex.
RwLockExtensions
Extension trait providing safe read lock acquisition for RwLock.

Functions§

from_poison_error
Utility function to convert from PoisonError to DMSCLockError.

Type Aliases§

DMSCLockResult
Result type alias for lock operations.