romushqa
romushqa

Reputation: 61

How to get the value, who first returned one of the threads

I'm need handle who first return not nil value from one of the threads and kill other threads.
For example i have this code:

require 'benchmark'
a = nil
puts "I'm need 1 second for test..."
result_time = Benchmark.measure {
    while true
      t1 = Thread.new { a = nil unless a } unless t1
      t2 = Thread.new { a = 1 unless a; sleep 1 } unless t2
      t3 = Thread.new { a = 1 unless a; sleep 2 } unless t3
      t1.join
      t2.join
      t3.join
      if !a.nil?
        t1.kill if t1
        t2.kill if t2
        t3.kill if t3
        break
      end
    end
}.real

if result_time >= 2.0
  puts "Bad. More than 1 second. result_time: #{result_time}"
else
  puts "Cool. Less than 2 seconds."
end

This code returned:

I'm need 1 second for test...
Bad. More than 1 second. result_time: 2.00074989994755
So i want 1 second for this test (not 2). Please help and sorry for my english:)

Upvotes: 0

Views: 88

Answers (1)

romushqa
romushqa

Reputation: 61

I just delete t1.join, t2.join and t3.join...Becouse method .join stop main thread. But don't know why result time >= 1 and <=2. I think sleep instuction not been executed, becouse main thread just kill second when a = 1 in while loop without waiting sleep insturuction. Final code:

require 'benchmark'
a = nil
puts "I'm need 1 second for test"
result_time = Benchmark.measure {
    while true
      t1 = Thread.new { a = nil unless a } unless t1
      t2 = Thread.new { a = 1 unless a; sleep 1 } unless t2
      t3 = Thread.new { a = 2 unless a; sleep 2 } unless t3
      if !a.nil?
        t1.kill if t1
        t2.kill if t2
        t3.kill if t3
        break
      end
    end
}.real

if result_time >= 2.0 puts "Bad. More than 1 second. result_time: #{result_time}. a: #{a}" else puts "Cool. Less than 2 seconds. result_time: #{result_time}. a: #{a}" end

Returned me:
I'm need 1 second for test
Cool. Less than 2 seconds. result_time: 0.001799600024241954. a: 1

Upvotes: 0

Related Questions