Debian Codegraph @

third_party/rust/triple_buffer/README.md

raw
1 # Triple buffering in Rust
2
3 [![On crates.io](https://img.shields.io/crates/v/triple_buffer.svg)](https://crates.io/crates/triple_buffer)
4 [![On docs.rs](https://docs.rs/triple_buffer/badge.svg)](https://docs.rs/triple_buffer/)
5 [![Continuous Integration](https://github.com/HadrienG2/triple-buffer/workflows/Continuous%20Integration/badge.svg)](https://github.com/HadrienG2/triple-buffer/actions?query=workflow%3A%22Continuous+Integration%22)
6 ![Requires rustc 1.36+](https://img.shields.io/badge/rustc-1.36+-red.svg)
7
8
9 ## What is this?
10
11 This is an implementation of triple buffering written in Rust. You may find it
12 useful for the following class of thread synchronization problems:
13
14 - There is one producer thread and one consumer thread
15 - The producer wants to update a shared memory value periodically
16 - The consumer wants to access the latest update from the producer at any time
17
18 The simplest way to use it is as follows:
19
20 ```rust
21 // Create a triple buffer:
22 let buf = TripleBuffer::new(0);
23
24 // Split it into an input and output interface, to be respectively sent to
25 // the producer thread and the consumer thread:
26 let (mut buf_input, mut buf_output) = buf.split();
27
28 // The producer can move a value into the buffer at any time
29 buf_input.write(42);
30
31 // The consumer can access the latest value from the producer at any time
32 let latest_value_ref = buf_output.read();
33 assert_eq!(*latest_value_ref, 42);
34 ```
35
36 In situations where moving the original value away and being unable to
37 modify it on the consumer's side is too costly, such as if creating a new
38 value involves dynamic memory allocation, you can use a lower-level API
39 which allows you to access the producer and consumer's buffers in place
40 and to precisely control when updates are propagated:
41
42 ```rust
43 // Create and split a triple buffer
44 use triple_buffer::TripleBuffer;
45 let buf = TripleBuffer::new(String::with_capacity(42));
46 let (mut buf_input, mut buf_output) = buf.split();
47
48 // Mutate the input buffer in place
49 {
50 // Acquire a reference to the input buffer
51 let input = buf_input.input_buffer();
52
53 // In general, you don't know what's inside of the buffer, so you should
54 // always reset the value before use (this is a type-specific process).
55 input.clear();
56
57 // Perform an in-place update
58 input.push_str("Hello, ");
59 }
60
61 // Publish the above input buffer update
62 buf_input.publish();
63
64 // Manually fetch the buffer update from the consumer interface
65 buf_output.update();
66
67 // Acquire a mutable reference to the output buffer
68 let output = buf_output.output_buffer();
69
70 // Post-process the output value before use
71 output.push_str("world!");
72 ```
73
74
75 ## Give me details! How does it compare to alternatives?
76
77 Compared to a mutex:
78
79 - Only works in single-producer, single-consumer scenarios
80 - Is nonblocking, and more precisely bounded wait-free. Concurrent accesses will
81 be slowed down by cache contention, but no deadlock, livelock, or thread
82 scheduling induced slowdown is possible.
83 - Allows the producer and consumer to work simultaneously
84 - Uses a lot more memory (3x payload + 3x bytes vs 1x payload + 1 bool)
85 - Does not allow in-place updates, as the producer and consumer do not access
86 the same memory location
87 - Should be slower if updates are rare and in-place updates are much more
88 efficient than moves, comparable or faster otherwise.
89 * Mutexes and triple buffering have comparably low overhead on the happy path
90 (checking a flag), which is systematically taken when updates are rare. In
91 this scenario, in-place updates can give mutexes a performance advantage.
92 Where triple buffering shines is when a reader often collides with a writer,
93 which is handled very poorly by mutexes.
94
95 Compared to the read-copy-update (RCU) primitive from the Linux kernel:
96
97 - Only works in single-producer, single-consumer scenarios
98 - Has higher dirty read overhead on relaxed-memory architectures (ARM, POWER...)
99 - Does not require accounting for reader "grace periods": once the reader has
100 gotten access to the latest value, the synchronization transaction is over
101 - Does not use the compare-and-swap hardware primitive on update, which is
102 inefficient by design as it forces its users to retry transactions in a loop.
103 - Does not suffer from the ABA problem, allowing much simpler code
104 - Allocates memory on initialization only, rather than on every update
105 - May use more memory (3x payload + 3x bytes vs 1x pointer + amount of
106 payloads and refcounts that depends on the readout and update pattern)
107 - Should be slower if updates are rare, faster if updates are frequent
108 * The RCU's happy reader path is slightly faster (no flag to check), but its
109 update procedure is much more involved and costly.
110
111 Compared to sending the updates on a message queue:
112
113 - Only works in single-producer, single-consumer scenarios (queues can work in
114 other scenarios, although the implementations are much less efficient)
115 - Consumer only has access to the latest state, not the previous ones
116 - Consumer does not *need* to get through every previous state
117 - Is nonblocking AND uses bounded amounts of memory (with queues, it's a choice,
118 unless you use one of those evil queues that silently drop data when full)
119 - Can transmit information in a single move, rather than two
120 - Should be faster for any compatible use case.
121 * Queues force you to move data twice, once in, once out, which will incur a
122 significant cost for any nontrivial data. If the inner data requires
123 allocation, they force you to allocate for every transaction. By design,
124 they force you to store and go through every update, which is not useful
125 when you're only interested in the latest version of the data.
126
127 In short, triple buffering is what you're after in scenarios where a shared
128 memory location is updated frequently by a single writer, read by a single
129 reader who only wants the latest version, and you can spare some RAM.
130
131 - If you need multiple producers, look somewhere else
132 - If you need multiple consumers, you may be interested in my related "SPMC
133 buffer" work, which basically extends triple buffering to multiple consumers
134 - If you can't tolerate the RAM overhead or want to update the data in place,
135 try a Mutex instead (or possibly an RWLock)
136 - If the shared value is updated very rarely (e.g. every second), try an RCU
137 - If the consumer must get every update, try a message queue
138
139
140 ## How do I know your unsafe lock-free code is working?
141
142 By running the tests, of course! Which is unfortunately currently harder than
143 I'd like it to be.
144
145 First of all, we have sequential tests, which are very thorough but obviously
146 do not check the lock-free/synchronization part. You run them as follows:
147
148 $ cargo test
149
150 Then we have concurrent tests where, for example, a reader thread continuously
151 observes the values from a rate-limited writer thread, and makes sure that he
152 can see every single update without any incorrect value slipping in the middle.
153
154 These tests are more important, but also harder to run because one must first
155 check some assumptions:
156
157 - The testing host must have at least 2 physical CPU cores to test all possible
158 race conditions
159 - No other code should be eating CPU in the background. Including other tests.
160 - As the proper writing rate is system-dependent, what is configured in this
161 test may not be appropriate for your machine.
162 - You must test in release mode, as compiler optimizations tend to create more
163 opportunities for race conditions.
164
165 Taking this and the relatively long run time (~10-20 s) into account, the
166 concurrent tests are ignored by default. To run them, make sure nothing is
167 eating CPU in the background and do:
168
169 $ cargo test --release -- --ignored --nocapture --test-threads=1
170
171 Finally, we have benchmarks, which allow you to test how well the code is
172 performing on your machine. We are now using `criterion` for said benchmarks,
173 which seems that to run them, you can simply do:
174
175 $ cargo bench
176
177 These benchmarks exercise the worst-case scenario of `u8` payloads, where
178 synchronization overhead dominates as the cost of reading and writing the
179 actual data is only 1 cycle. In real-world use cases, you will spend more time
180 updating buffers and less time synchronizing them.
181
182 However, due to the artificial nature of microbenchmarking, the benchmarks must
183 exercise two scenarios which are respectively overly optimistic and overly
184 pessimistic:
185
186 1. In uncontended mode, the buffer input and output reside on the same CPU core,
187 which underestimates the overhead of transferring modified cache lines from
188 the L1 cache of the source CPU to that of the destination CPU.
189 * This is not as bad as it sounds, because you will pay this overhead no
190 matter what kind of thread synchronization primitive you use, so we're not
191 hiding `triple-buffer` specific overhead here. All you need to do is to
192 ensure that when comparing against another synchronization primitive, that
193 primitive is benchmarked in a similar way.
194 2. In contended mode, the benchmarked half of the triple buffer is operating
195 under maximal load from the other half, which is much more busy than what is
196 actually going to be observed in real-world workloads.
197 * In this configuration, what you're essentially measuring is the performance
198 of your CPU's cache line locking protocol and inter-CPU core data
199 transfers under the shared data access pattern of `triple-buffer`.
200
201 Therefore, consider these benchmarks' timings as orders of magnitude of the best
202 and the worst that you can expect from `triple-buffer`, where actual performance
203 will be somewhere inbetween these two numbers depending on your workload.
204
205 On an Intel Core i3-3220 CPU @ 3.30GHz, typical results are as follows:
206
207 * Clean read: 0.9 ns
208 * Write: 6.9 ns
209 * Write + dirty read: 19.6 ns
210 * Dirty read (estimated): 12.7 ns
211 * Contended write: 60.8 ns
212 * Contended read: 59.2 ns
213
214
215 ## License
216
217 This crate is distributed under the terms of the MPLv2 license. See the LICENSE
218 file for details.
219
220 More relaxed licensing (Apache, MIT, BSD...) may also be negociated, in
221 exchange of a financial contribution. Contact me for details at
222 knights_of_ni AT gmx DOTCOM.