Skip to main content

Crate doublebuf

Crate doublebuf 

Source
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_std usage is explicitly allowed, but a critical_section implementation must be provided.
  • In std contexts, you may enable the std feature of critical_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::read or Accessor::write methods.
DoubleBuf
A thread-safe double buffer with automatic swapping. See module-level documentation for general notes. The usual workflow is as follows:
ReadGuard
WriteGuard