开发者

why the sleep statement produces this result for our embedded ruby?

We are testing thread coperation for our embedded ruby. We have a C ruby extension implementented the following methods

1. longRunningMethod()
2. shortRunningMethod().

Here is a code for the checking the thread cooperation

//file test.rb

require 'mymodule'

$a = 0;
obj = MyModule::MyClass.new
t1 = Thread.new{$a = obj.veryLongRunningOperation(); puts "doneLong"}
sleep 1
$a = obj.shortOperation()
puts "doneShort"
开发者_JAVA技巧t1.join

We have ensured that the longRunningMethod takes more than 1sec(5sec) for execution using nested for loops As per our understanding, the shortRunningMethod should be completed first and then longRunningMethod.

However we observed this only when we did not have any sleep command. But when we introduced the "sleep 1" statement. The longRunningMethod gets executed first and then shortRunningMethod

Anyone would give us the pointers as to why the sleep statement produces this result?

[We are using ruby 1.8.6] Thanks in advance.


Threads in Ruby 1.8 do not use native OS threading mechanisms. All Ruby threads, are actually run within one native thread (no parallel execution).

Your C methods are atomic, so that thread scheduler waits until they return, before switching Ruby threads. That's why once it starts doing longRunningMethod before it gets to shortRunningMethod it does nothing else until it's finished. You're experiencing what is called a 'thread starvation'.

One way to avoid it, is to implement your longRunningMethod in such a way, so that it periodically calls sleep itself.


Is the thread automatically started as soon as it is created? In Java, one has to call t1.start() explicitly to start the thread. Maybe it's the same in Ruby.

t1.join could have the extra functionality that it chcks whether the thread has started already, and if it hasn't, it is started.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜