开发者

why their is difference in output of ruby script?

I have follwing ruby scripts rubyScript.rb:

require "rScript"
t1 = Thread.new{LongRunningOperation(); puts "doneLong"}
     sleep 1
     shortOperation()
     puts "doneShort"
     t1.join

rScript.rb:

def LongRunningOperation()
  puts "In LongRunningOperation method"
  for i in 0..100000
  end
 return 0开发者_如何转开发
end
def shortOperation()
  puts "IN shortOperation method"
  return 0
end

THE OUTPUT of above script i.e.(ruby rubyScript.rb)

1) With use of sleep function

In veryLongRunningOperation method
doneLong
IN shortOperation method
doneShort

2) Without use of sleep function i.e. removing sleep function.(ruby rubyScript.rb)

In veryLongRunningOperation method
IN shortOperation method
doneShort
doneLong

why there is difference in output. What sleep does in ablve case. Thannks in advance.


The sleep lets the main thread sleep for 1 second. Your long running function runs longer than your short running function but it is still faster than one second.

If you remove the sleep, then your long running function starts in a new thread and the main thread continues without any wait. It then starts the short running function, which finishes nearly immediatly, while the long running function is still running.

In the case of the none removed sleep it goes as following: Your long running function starts in a new Thread and the main thread continues. Now the main thread encounters the sleep command and waits for 1 second. In this time the long running function in the other thread is still running and finishes. The main thread continues after its sleep time and starts the short running function.


sleep 1 makes the current thread sleep (i.e. do nothing) for one second. So veryLongRunningOperation (which despite being a very long running operation still takes less than a second) has enough time to finish before shortOperation even starts.


sleep 1

Makes the main thread to wait for 1 second, that allows t1 to finish before shortOperation is executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜