Quiz 1

Questions relating to the Threading API are covered in this lesson.

Question#1

Consider the snippet below:

Thread.current.name = "mainThread"

# Spawn a child thread
thread = Thread.new do

  thread.exit()
  puts("Child thread exiting")
end


thread.join()

puts("Main thread exiting")

Q

Is the statement “Child thread exiting” get printed?

A)

Yes

B)

No

C)

Intrepreter throws unreachable code error

Press + to interact
Thread.current.name = "mainThread"
# Spawn a child thread
thread = Thread.new do
thread.exit()
puts("Child thread exiting")
end
thread.join()
puts("Main thread exiting")

Question#2

Consider the code snippet below:

Thread.new do

  while true
    sleep(1)
  end
  puts("Child thread exiting")
end

puts("Main thread exiting")
Q

Is the statement in the spawned thread printed?

A)

Yes

B)

No

C)

Maybe

Press + to interact
Thread.new do
while true
sleep(1)
end
puts("Child thread exiting")
end
puts("Main thread exiting")

Explanation

It might surprise you that the correct answer is maybe even though if you run the widget several times, only the line from the main thread is printed on the console. Threads scheduling can be non-deterministic and it is possible that the spawned thread is immediately scheduled when created and prints on the console, before the main thread exits.

Question#3

Consider the snippet below:

"Main thread executing"
Thread.stop
Q

What is outcome of running the above snippet?

A)

program exits

B)

program hangs

C)

Interpreter throws an error

Press + to interact
"Main thread executing"
Thread.stop

Question#4

Consider the snippet below:

mutex = Mutex.new

Thread.new do
  mutex.lock()
  puts("Child thread exiting")
end

# wait for child thread to exit
sleep(2)
puts("Is mutex locked #{mutex.locked?}")
mutex.lock()
Q

What is the outcome of running the program?

A)

Program hangs because the child thread exits without unlocking mutex

B)

Program continues normally and the mutex is reverted to the unlocked state by the interpreter when the child thread exits

C)

Interpreter throws an exception

Press + to interact
mutex = Mutex.new
Thread.new do
mutex.lock()
puts("Child thread exiting")
end
# wait for child thread to exit
sleep(2)
puts("Is mutex locked #{mutex.locked?}")
mutex.lock()

Question#5

Consider the snippet below, where the main thread join()-s a child thread after the child thread has finished:

thread = Thread.new do
  puts "Child thread exits"
end

sleep(2)

# main thread joins an already completed thread
thread.join()
Q

What is the outcome of the program?

A)

An error is thrown because the child thread has already finished

B)

The main thread returns immediately from the join() method because the child thread has finished and continues normally

Press + to interact
thread = Thread.new do
puts "Child thread exits"
end
sleep(2)
# main thread joins an already completed thread
thread.join()