The most fundamental cause of thread safety issues is shared mutable state (e.g., class instance variables, module variables, or shared mutable objects). In environments with multiple execution contexts like fibers or threads, shared mutable state creates unpredictable execution paths.
Best Practices:
- Avoid sharing mutable state whenever possible.
- Prefer isolation, immutability, and pure functions.
- If shared state is necessary, use coordination primitives like
Mutex or concurrent data structures, but be aware of deadlocks and contention.
class CurrencyConverter
def initialize
@exchange_rates = {} # Issue: Shared mutable state
end
def update_rate(currency, rate)
# Issue: Multiple threads can modify @exchange_rates concurrently
@exchange_rates[currency] = rate
end
def convert(amount, from_currency, to_currency)
# Issue: If @exchange_rates is modified while this method runs, it can lead to incorrect conversions
rate = @exchange_rates[from_currency] / @exchange_rates[to_currency]
amount * rate
end
end