0
0
Rubyprogramming~30 mins

Thread safety concepts in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Thread Safety Concepts in Ruby
📖 Scenario: Imagine you are building a simple bank system where multiple people can deposit money into the same account at the same time. To keep the account balance correct, you need to make sure that the updates to the balance are done safely when many threads work together.
🎯 Goal: You will create a Ruby program that shows how to safely update a shared bank account balance using thread safety concepts.
📋 What You'll Learn
Create a shared bank account balance variable
Create a mutex lock to control access to the balance
Use multiple threads to deposit money safely
Print the final balance after all deposits
💡 Why This Matters
🌍 Real World
Thread safety is important in real-world programs where many tasks run at the same time and share data, like banking apps or online stores.
💼 Career
Understanding thread safety helps you write reliable and bug-free code in jobs that involve concurrent programming or server-side development.
Progress0 / 4 steps
1
Create the shared bank account balance
Create a variable called balance and set it to 0 to represent the starting bank account balance.
Ruby
Need a hint?

Use a simple variable assignment like balance = 0.

2
Create a mutex lock for thread safety
Create a variable called mutex and set it to a new Mutex object to control access to the shared balance.
Ruby
Need a hint?

Use Mutex.new to create a new lock.

3
Use threads to deposit money safely
Create 5 threads that each add 100 to balance safely using mutex.synchronize to lock the update. Use a variable called threads to store the thread objects.
Ruby
Need a hint?

Use 5.times do to create threads, and inside each thread use mutex.synchronize to safely update balance.

4
Print the final balance
Write a puts statement to print the final value of balance after all threads have finished.
Ruby
Need a hint?

Use puts balance to show the final amount.