Arc/Mutex Performance
How slow is using Arc<Mutex<T>> in Rust? Is there any cheaper way to share data between threads? I'm writing a NES emulator and in my project I have several bools that need to be shared. Some of them are for checking if the threads should break the loop.
Note: I have three threads overall: main window, debugger window and emulator.
Benchmark Edit: Each locking of the <Arc<Mutex<bool>> takes ~201 ns while the rest of the loop takes (with a single <Arc<Mutex<CPU>> lock) ~418 ns. If I remove the CPU lock, it drops to ~90 ns.
Benchmark Edit 2: Those are the results I got after benchmarking (three runs of each):
Arc<AtomicBool>:
117 ns
167 ns
146 ns
Arc<Mutex<bool>>:
261 ns
219 ns
237 ns
Apparently, Arc<AtomicBool> is ~67% faster in this case (average).
After replacing all Arc<Mutex<bool>> by Arc<AtomicBool>, those are the results for a whole loop cycle:
Arc<AtomicBool>
383 ns
437 ns
332 ns
<Arc<Mutex<bool>>
465 ns
535 ns
416 ns
Arc<AtomicBool> is ~23% faster than Arc<Mutex<bool>> (average).
After that, I've replaced Arc<Mutex<u64>> by `` and those are the results:
Arc<Mutex<u64>>:
(single lock):
184 ns
94 ns
99 ns
(loop):
964 ns
579 ns
515 ns
Arc<RwLock<u64>>:
(single write):
171 ns
181 ns
201 ns
(write + loop):
430 ns
407 ns
423 ns
Even though RwLock<T> is slightly slower for isolated write() locks, it's ~63% faster in a whole loop cycle and has more stable timings (average).