I’m running the following example:
#!/usr/bin/env ruby
-- coding: utf-8 --
require ‘thread’
mutex = Mutex.new
cv = ConditionVariable.new
a = Thread.new {
mutex.synchronize {
puts “A: I have critical section, but will wait for cv”
cv.wait(mutex)
puts “A: I have critical section again! I rule!”
}
}
puts “(Later, back at the ranch…)”
b = Thread.new {
mutex.synchronize {
puts “B: Now I am critical, but am done with cv”
cv.signal
puts “B: I am still critical, finishing up”
}
}
a.join
b.join
which gives me the following output:
(Later, back at the ranch…)
A: I have critical section, but will wait for cv
B: Now I am critical, but am done with cv
B: I am still critical, finishing up
A: I have critical section again! I rule!
However, the tutorial which gave me this example illustrates that the
output should be the following:
A: I have critical section, but will wait for cv
(Later, back at the ranch…)
B: Now I am critical, but am done with cv
B: I am still critical, finishing up
A: I have critical section again! I rule!
But I can only get this output when I put
“sleep(0.000_000_000_000_000_1)”
before the “puts” statement in the main thread. So, why is the main
thread
running before thread a?