README.rst 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. range-lock - Multithread range lock for Vec
  2. ===========================================
  3. `Project home <https://bues.ch/>`_
  4. `Git repository <https://bues.ch/cgit/rangelockrs.git>`_
  5. `Github repository <https://github.com/mbuesch/rangelockrs>`_
  6. This crate provides locks/mutexes for multi-threaded access to a single Vec<T> instance.
  7. Any thread can request exclusive access to a slice of the Vec.
  8. Such access is granted, if no other thread is simultaneously holding the permission to access an overlapping slice.
  9. Usage
  10. =====
  11. Add this to your Cargo.toml:
  12. .. code:: toml
  13. [dependencies]
  14. range-lock = "0.2"
  15. VecRangeLock example usage
  16. --------------------------
  17. General purpose VecRangeLock:
  18. .. code:: rust
  19. use range_lock::VecRangeLock;
  20. use std::sync::Arc;
  21. use std::thread;
  22. let lock = Arc::new(VecRangeLock::new(vec![1, 2, 3, 4, 5]));
  23. thread::spawn(move || {
  24. let mut guard = lock.try_lock(2..4).expect("Failed to lock range 2..4");
  25. assert_eq!(guard[0], 3);
  26. guard[0] = 10;
  27. });
  28. RepVecRangeLock example usage
  29. -----------------------------
  30. The RepVecRangeLock is a restricted range lock, that provides access to interleaved patterns of slices to the threads.
  31. Locking a RepVecRangeLock is more lightweight than locking a VecRangeLock.
  32. The threads can not freely choose slice ranges, but only choose a repeating slice pattern by specifying a pattern offset.
  33. Please see the example below.
  34. .. code:: rust
  35. use range_lock::RepVecRangeLock;
  36. use std::sync::Arc;
  37. use std::thread;
  38. let data = vec![1, 2, 3, // <- cycle 0
  39. 4, 5, 6]; // <- cycle 1
  40. // ^ ^ ^
  41. // | | |
  42. // | | offset-2
  43. // offset-0 offset-1
  44. let lock = Arc::new(RepVecRangeLock::new(data,
  45. 1, // slice_len: Each slice has 1 element.
  46. 3)); // cycle_len: Each cycle has 3 slices (offsets).
  47. thread::spawn(move || {
  48. // Lock slice offset 1:
  49. let mut guard = lock.try_lock(1).expect("Failed to lock offset.");
  50. assert_eq!(guard[0][0], 2); // Cycle 0, Slice element 0
  51. assert_eq!(guard[1][0], 5); // Cycle 1, Slice element 0
  52. guard[0][0] = 20; // Cycle 0, Slice element 0
  53. guard[1][0] = 50; // Cycle 1, Slice element 0
  54. });
  55. TODOs for future releases
  56. =========================
  57. The following new features might be candidates for future releases:
  58. * Sleeping lock, in case of lock contention.
  59. * Add support for arrays.
  60. License
  61. =======
  62. Copyright (c) 2021-2023 Michael Büsch <m@bues.ch>
  63. Licensed under the Apache License version 2.0 or the MIT license, at your option.