You can easily verify the priority of the main thread:
main_thread.rb
puts( Thread.main.priority ) #=> 0
So, in the previous program (threads4.rb), if you set the priority of t1
to 2, it will “outrank” the main thread itself and will then be given all the execution time it needs until the next thread, t2
, comes along, and so on. By setting the priorities lower than that of the main thread, you can force the three threads to compete only with themselves since the main thread will always outrank them. If you prefer working with positive numbers, you can specifically set the priority of the main thread to a higher value than all other threads:
Thread.main.priority=100
Ruby 1.9 may not respect all values assigned in this way. For example, when I display that the priority of a thread to 100 has been assigned, Ruby 1.9 shows 3, whereas Ruby 1.8 shows 100.
If you want t2
and t3
to have the same priority and t1
to have a lower one, you need to set the priorities for those three threads plus the main thread:
threads5.rb
Thread.main.priority = 200 t1.priority = 0 t2.priority = 1 t3.priority = 1
Once again, this assumes you are using a version of Ruby (such as Ruby 1.8) in which thread priorities are respected. If you look closely at the output, you may spot one tiny but undesirable side effect. It is possible (not certain, but possible) that you will see some output from the t1
thread right at the outset, just before t2
and t3
kick in and assert their priorities. This is the same problem noted earlier: Each of the threads tries to start running as soon as it is created, and t1
may get its own slice of the action before the priorities of the other threads are “upgraded.” To prevent this, you can specifically suspend the thread at the time of creation using Thread.stop
like this:
stop_run.rb
t1 = Thread.new{ Thread.stop 0.upto(50){print( "t1 " )} }
Now, when you want to start the thread running (in this case, after setting the thread priorities), you call its run
method:
t1.run
Note that the use of some Thread methods may cause deadlocks in Ruby 1.9. A deadlock occurs when two or more threads are waiting for one another to release a resource. To avoid deadlocks, you may prefer to use mutexes, as I’ll explain next.
18.221.197.95