码迷,mamicode.com
首页 > 编程语言 > 详细

Ruby之多线程

时间:2014-11-28 18:12:35      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   数据   

#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 

 

Ruby之多线程

标签:style   blog   io   ar   color   sp   for   on   数据   

原文地址:http://www.cnblogs.com/xueyuwyz/p/4128970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!