README.rst 2.7 KB

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