range_lock/lib.rs
1// -*- coding: utf-8 -*-
2//
3// Copyright 2021-2023 Michael Büsch <m@bues.ch>
4//
5// Licensed under the Apache License version 2.0
6// or the MIT license, at your option.
7// SPDX-License-Identifier: Apache-2.0 OR MIT
8//
9
10//! This crate provides locks/mutexes for multi-threaded access to a single [std::vec::Vec] instance.
11//!
12//! # VecRangeLock: General purpose range lock
13//!
14//! This is a very basic usage example.
15//! For a more complex example, please see the [VecRangeLock] struct documentation.
16//!
17//! ```
18//! use range_lock::VecRangeLock;
19//! use std::sync::Arc;
20//! use std::thread;
21//!
22//! let lock = Arc::new(VecRangeLock::new(vec![1, 2, 3, 4, 5]));
23//!
24//! thread::spawn(move || {
25//! let mut guard = lock.try_lock(2..4).expect("Failed to lock range 2..4");
26//! assert_eq!(guard[0], 3);
27//! guard[0] = 10;
28//! });
29//! ```
30//!
31//! # RepVecRangeLock: Restricted interleaved pattern range lock
32//!
33//! This is a very basic usage example.
34//! For a more complex example, please see the [RepVecRangeLock] struct documentation.
35//!
36//! ```
37//! use range_lock::RepVecRangeLock;
38//! use std::sync::Arc;
39//! use std::thread;
40//!
41//! let data = vec![1, 2, 3, // <- cycle 0
42//! 4, 5, 6]; // <- cycle 1
43//! // ^ ^ ^
44//! // | | |
45//! // | | offset-2
46//! // offset-0 offset-1
47//!
48//! let lock = Arc::new(RepVecRangeLock::new(data,
49//! 1, // slice_len: Each slice has 1 element.
50//! 3)); // cycle_len: Each cycle has 3 slices (offsets).
51//! thread::spawn(move || {
52//! // Lock slice offset 1:
53//! let mut guard = lock.try_lock(1).expect("Failed to lock offset.");
54//!
55//! assert_eq!(guard[0][0], 2); // Cycle 0, Slice element 0
56//! assert_eq!(guard[1][0], 5); // Cycle 1, Slice element 0
57//!
58//! guard[0][0] = 20; // Cycle 0, Slice element 0
59//! guard[1][0] = 50; // Cycle 1, Slice element 0
60//! });
61//! ```
62
63mod lockedranges;
64mod rangelock;
65mod reprangelock;
66mod util;
67mod vecparts;
68
69pub use rangelock::{VecRangeLock, VecRangeLockGuard};
70pub use reprangelock::{RepVecRangeLock, RepVecRangeLockGuard};
71
72// vim: ts=4 sw=4 expandtab