docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#Bank transfers

On this page

Several threads move money between accounts guarded by Mutex, collect statistics in Atomic counters, and finally check that the total never changed.

#Code

#Walkthrough

  • Each account is its own Mutex<i64>, kept in a fixed array. A List would not compile here: lists are shared mutable handles and are not Sync, so a thread closure may not capture one (4.6.9). The lock is taken with using g = m.lock() { ... } and released when the block ends; the guarded value is read and written with get() / set(). To only read it, m.with(|v| v) takes the lock for one call, as total does (Concurrency, 3.17 using, Mutex).
  • A transfer must lock both accounts. If two threads ran A→B and B→A at the same time and locked in opposite order, they could wait for each other forever, so the lower-numbered account is always locked first.
  • Independent counters, such as the amount moved and the number of rejections, are counted without a lock using fetch_add on Atomic<i64> (Atomic, 2.16 sync).
  • Each thread draws from its own seeded generator, random::Xoshiro256PlusPlus::seed(..): below(n) gives a value in 0..n and range(1..301) an amount, the same sequence on every run for the same seed (random).
  • The balance of each account depends on how the threads interleave, but if transfers are atomic the total is always the same. The output contains only facts that do not depend on that order.

Found a mistake? Edit this page on GitHub. Last updated