Expand description
This crate implements a thread-safe double buffer with automatic swapping.
DoubleBuf is a data structure with two buffers (buffer 1 and buffer 2) and two users,
each having exclusive access to one of the buffers. The users can request read or write access
to the underlying buffer (we say that a user is active while it keeps this access), such that the following holds:
Whenever both users are inactive with at least one having requested write access since the last swap, the two buffers are atomically swapped.
Note that while we use the term “buffer”, any type T is allowed.
§Usage
use doublebuf::*;
let mut db: DoubleBuf<u8> = DoubleBuf::new();
let (back, front) = db.init();
let mut writer = back.write();
let reader = front.read();
// Both are initialized with the default value
assert_eq!(*reader, 0);
assert_eq!(*writer, 0);
*writer = 5;
drop(writer);
drop(reader);
// the buffers are swapped now!
let reader = front.read();
assert_eq!(*reader, 5);§Notes
no_stdusage is explicitly allowed, but acritical_sectionimplementation must be provided.- In
stdcontexts, you may enable thestdfeature ofcritical_section. - While double buffers conventionally have a “front” and a “back” buffer (the back buffer being used by the producer and the front buffer by the consumer), our implementation is completely symmetric.
- The buffers are not swapped if there has been no write access since the last swap.
- The semantics allow for a live-lock: If the two accessors are continuously overlapping their accesses (that is, if there is no point in time when neither is inactive), the buffers will never get swapped.
Structs§
- Accessor
- A user of the double buffer. There can only ever be exactly two Accessors associated with one initialized double buffer.
The accessor is exclusively associated to one of the two buffers, and can obtain access using the
Accessor::readorAccessor::writemethods. - Double
Buf - A thread-safe double buffer with automatic swapping. See module-level documentation for general notes. The usual workflow is as follows:
- Read
Guard - Write
Guard