Skip to content

Commit

Permalink
Merge pull request #199 from garious/add-accounting-stage
Browse files Browse the repository at this point in the history
Fix race condition in Accountant::apply_payment()
  • Loading branch information
garious authored May 11, 2018
2 parents 8a9f6b9 + 1acd2aa commit a485c14
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/accountant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,19 @@ pub type Result<T> = result::Result<T, AccountingError>;

/// Commit funds to the 'to' party.
fn apply_payment(balances: &RwLock<HashMap<PublicKey, AtomicIsize>>, payment: &Payment) {
// First we check balances with a read lock to maximize potential parallelization.
if balances.read().unwrap().contains_key(&payment.to) {
let bals = balances.read().unwrap();
bals[&payment.to].fetch_add(payment.tokens as isize, Ordering::Relaxed);
} else {
// Now we know the key wasn't present a nanosecond ago, but it might be there
// by the time we aquire a write lock, so we'll have to check again.
let mut bals = balances.write().unwrap();
bals.insert(payment.to, AtomicIsize::new(payment.tokens as isize));
if bals.contains_key(&payment.to) {
bals[&payment.to].fetch_add(payment.tokens as isize, Ordering::Relaxed);
} else {
bals.insert(payment.to, AtomicIsize::new(payment.tokens as isize));
}
}
}

Expand Down

0 comments on commit a485c14

Please sign in to comment.