0
0
Rubyprogramming~10 mins

Why concurrency matters in Ruby - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new thread that prints 'Hello from thread!'.

Ruby
thread = Thread.new { puts [1] }
thread.join
Drag options to blanks, or click blank then click option'
A"Hello from thread!"
BHello from thread!
Cprint 'Hello from thread!'
Dputs Hello from thread!
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the string.
Using print instead of puts inside the thread block.
2fill in blank
medium

Complete the code to start two threads that each print a different message.

Ruby
t1 = Thread.new { puts [1] }
t2 = Thread.new { puts [2] }
t1.join
t2.join
Drag options to blanks, or click blank then click option'
A"Thread 1 running"
B"Thread 2 running"
C"Running thread"
D"Thread running"
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the string.
Using the same message for both threads.
3fill in blank
hard

Fix the error in the code to safely increment a shared counter using a Mutex.

Ruby
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
Drag options to blanks, or click blank then click option'
Asynchronize
Bunlock
Cwait
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using lock without unlocking.
Using unlock directly.
Using wait which is not a Mutex method.
4fill in blank
hard

Fill both blanks to create a thread that sleeps for 2 seconds and then prints a message.

Ruby
thread = Thread.new do
  sleep [1]
  puts [2]
end
thread.join
Drag options to blanks, or click blank then click option'
A2
B"Done sleeping"
C"Sleeping done"
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around the number 2.
Not quoting the message string.
5fill in blank
hard

Fill all three blanks to create a thread-safe counter increment using Mutex and threads.

Ruby
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
Drag options to blanks, or click blank then click option'
Asynchronize
B+=
C==
Dlock
Attempts:
3 left
💡 Hint
Common Mistakes
Using lock without unlocking.
Using = instead of +=.
Using = instead of == for comparison.