Complete the code to create a new thread that prints 'Hello from thread!'.
thread = Thread.new { puts [1] }
thread.joinIn Ruby, strings must be quoted. To print the message, we use puts with a quoted string.
Complete the code to start two threads that each print a different message.
t1 = Thread.new { puts [1] }
t2 = Thread.new { puts [2] }
t1.join
t2.joinThe first thread prints "Thread 1 running" and the second prints "Thread 2 running".
Fix the error in the code to safely increment a shared counter using a Mutex.
counter = 0 mutex = Mutex.new threads = [] 5.times do threads << Thread.new do mutex.[1] do counter += 1 end end end threads.each(&:join) puts counter
lock without unlocking.unlock directly.wait which is not a Mutex method.To safely access shared data in Ruby threads, use Mutex#synchronize which locks and unlocks automatically.
Fill both blanks to create a thread that sleeps for 2 seconds and then prints a message.
thread = Thread.new do sleep [1] puts [2] end thread.join
The thread sleeps for 2 seconds, then prints the message 'Done sleeping'.
Fill all three blanks to create a thread-safe counter increment using Mutex and threads.
counter = 0 mutex = Mutex.new threads = [] 10.times do threads << Thread.new do mutex.[1] do counter [2] 1 end end end threads.each(&:join) puts counter [3] 10
lock without unlocking.= instead of +=.= instead of == for comparison.Use synchronize to lock the counter increment safely, += to add 1, and == to check the final value.