Ruby之多线程

#Thread #1 is running here
Thread.new{
  #Thread #2 runs this code
}
#Thread #1 runs this code

Thread.new的同义词是Thread.start和Thread.for

代码块中的最后一个表达式的值是线程的值,可以通过调用Thread对象的值的方法获得。

Thread.current   表示当前线程的Thread对象。

Thread.main  代表ruby程序的开始时的主线程

Thread.join  阻塞当前线程知道join的线程执行完毕

Thread.abort_on_exception = true  如果有未处理的异常则退出解释器

线程中可以存储属于线程的数据

Thread.current[count] = 0

puts Thread.current[count]

线程互斥

#!/usr/bin/ruby
require thread
mutex = Mutex.new

count1 = count2 = 0
difference = 0
counter = Thread.new do
   loop do
      mutex.synchronize do
         count1 += 1
         count2 += 1
      end
    end
end
spy = Thread.new do
   loop do
       mutex.synchronize do
          difference += (count1 - count2).abs
       end
   end
end
sleep 1
mutex.lock
puts "count1 :  #{count1}"
puts "count2 :  #{count2}"
puts "difference : #{difference}"

线程状态

Thread state  Return value
Runnable run
Sleeping Sleeping
Aborting aborting
Terminated normally false
Terminated width exception nil

 

#!/usr/bin/ruby

thr = Thread.new do   # Calling a class method new puts "In second thread"
   raise "Raise exception"
end
thr.join   # Calling an instance method join 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。