Fix race condition in concurrent deposit

Quick Overview

This question evaluates understanding of concurrency and thread safety, specifically recognizing race conditions and reasoning about synchronization for shared mutable state in multithreaded programs.

Fix race condition in concurrent deposit

Company: xAI

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Technical Screen

## Concurrent bank account debugging (thread safety) You are given a simple `BankAccount` object that is used concurrently from multiple threads. Two deposits run at the same time: ```python account = BankAccount(0) with ThreadPoolExecutor(max_workers=2) as executor: futures = [ executor.submit(account.deposit, 500), executor.submit(account.deposit, 700), ] ``` A simplified implementation of `deposit()` looks like this: ```python class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): new_balance = self.balance + amount # Read time.sleep(0.1) # Delay self.balance = new_balance # Write ``` ### Tasks 1. Explain why this code can produce an incorrect final balance (e.g., `700` instead of the expected `1200`). 2. Identify the underlying concurrency bug(s). 3. Propose and describe a correct fix that ensures thread safety for `deposit()`. 4. Mention any important caveats or alternatives (e.g., performance trade-offs, other synchronization approaches).

Quick Answer: This question evaluates understanding of concurrency and thread safety, specifically recognizing race conditions and reasoning about synchronization for shared mutable state in multithreaded programs.

|Home/Software Engineering Fundamentals/xAI
xAI logo
xAI
Dec 15, 2025, 12:00 AM
mediumSoftware EngineerTechnical ScreenSoftware Engineering Fundamentals
19
0

Concurrent bank account debugging (thread safety)

You are given a simple BankAccount object that is used concurrently from multiple threads. Two deposits run at the same time:

account = BankAccount(0)
with ThreadPoolExecutor(max_workers=2) as executor:
    futures = [
        executor.submit(account.deposit, 500),
        executor.submit(account.deposit, 700),
    ]

A simplified implementation of deposit() looks like this:

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        new_balance = self.balance + amount  # Read
        time.sleep(0.1)                      # Delay
        self.balance = new_balance           # Write

Tasks

  1. Explain why this code can produce an incorrect final balance (e.g., 700 instead of the expected 1200 ).
  2. Identify the underlying concurrency bug(s).
  3. Propose and describe a correct fix that ensures thread safety for deposit() .
  4. Mention any important caveats or alternatives (e.g., performance trade-offs, other synchronization approaches).
Loading comments...