In contrast to Ruby's less than ideal threading model (which is to change in 1.9), .NET has a rich threading model that we can tap into using IronRuby. We can create a new thread in IronRuby in the same way that we do in MRI Ruby:
Thread.new { puts "child thread" }
In IronRuby, however, we're not talking "green" threads. Instead, we get a real .NET thread as demonstrated in this example:
require "mscorlib"
include System::Threading
puts "##{Thread.current_thread.managed_thread_id} is the main thread."
# #1 is the main thread.
Thread.new { puts "##{Thread.current_thread.managed_thread_id} is a child thread." }
# #3 is a child thread.
You may have noticed that we didn't have to do anything to launch the thread. This is undesirable if you need to, for instance, start a thread as a background thread. Since the default value for the IsBackground property is false, the thread in the example above runs as a foreground thread. If your thread runs long enough, you can do this:
require "mscorlib"
include System::Threading
t = Thread.new { Thread.sleep 1000 }
puts "t.is_background = #{t.is_background}"
# t.is_background = false
t.is_background = true
puts "t.is_background = #{t.is_background}"
# t.is_background = true
Use of
Thread.new
will probably suffice in only the simplest situations. IronRuby supports more advanced threading scenarios and we'll get started on that in the next post in this series!
No comments:
Post a Comment