ProblemsConcurrencyThread-safe bank account
AdvancedConcurrency

Thread-safe bank account

Context

A Series-A fintech, motto 'move fast'. Money moves fast too: under concurrent transfers the balance sometimes adds up, sometimes doesn't. The CTO suggested 'adding sleep(10ms) so the threads don't collide'. The regulator would suggest something else. Make account operations actually atomic: a mutex and RAII locks.

Task

Implement a BankAccount that is safe to use from multiple threads. Operations on a closed account must be rejected.

Adapted from exercism/cpp (MIT).

Constraints

  • Guard all state with a std::mutex
  • No data races: concurrent deposits must sum exactly
  • open() resets the balance to 0; close() makes the account unusable
  • balance(), deposit(), withdraw() on a closed account must throw
  • deposit/withdraw reject negative amounts; withdraw rejects overdrafts

Before you code

  • Why must balance() also be protected by the mutex?
  • What happens to the total if two threads run deposit without a lock?
  • How would std::lock_guard help keep the critical section correct under exceptions?

Tests

  • #1Basic open / deposit / withdraw
  • #2Concurrent deposits sum correctly
  • #3Closed account rejects operations
  • #4Rejects negative amounts and overdrafts

Hints

Hint 1

Guard balance and open-state with a std::mutex locked via lock_guard in every method.

Hint 2

Throw from deposit/withdraw/balance when the account is closed or the amount is invalid.

Editorbank-account.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.