Ruby 多线程

# Thread.new { do_some_thing}
# 创建线程之后线程会执行代码块中的东西
# 像处理图片的话计算机CPU计算较多称为Compute-bound 上传下载的话是IO-bound
# Multiprocess vs Multithread

def foo
  10.times do
    puts "call foo at #{Time.now}"
  end
  sleep(0.5)
end

def bar
  10.times do
    puts "call bar at #{Time.now}"
  end
  sleep(0.5)
end

p "*"*10 + 'start' + "*"*10
t1 = Thread.new { foo }
t2 = Thread.new { bar }
t1.join # join 主线程会在这等待 t1线程执行完毕后再往下执行
t2.join
p "*"*10 + 'end' + "*"*10

# Thread.current
# 每个 Thread 都有自己的hash
count = 0
arr= []

10.times do |i|
  arr[i] = Thread.new do
    sleep(rand(0)/10.0)
    Thread.current["count"] = count
    count += 1
  end
end

arr.each do |t|
  t.join
  print t["count"], ","
end

puts "count = #{count}"

# Thread priority
# 线程的优先 priority 的值越大 越优先
count1 = count2 = 0
a = Thread.new do
  loop { count1 += 1}
end
a.priority = 1

b = Thread.new do
  loop { count2 += 1}
end
b.priority = -1

sleep 1
p count1
p count2

# Thread 中的异常
# 如果主线程再等待子线程 如果此时子线程发生异常则会上抛给主线程
# t1 = Thread.new do
#   puts "In new Thread"
#   raise "Exception from thread"
# end
# t1.join
# puts "not reached"

# 但如果主线程不等待的话 子线程就自己终止掉
# t1 = Thread.new do
#   puts "In new Thread"
#   raise "Exception from thread"
# end
# sleep 1
# puts "not reached"

# 但如果 Thread.abort_on_exception = true的话则不管主线程是否等待子线程的异常都会扔给主线程
# Thread.abort_on_exception = true
#
# t1 = Thread.new do
#   puts "In new Thread"
#   raise "Exception from thread"
# end
# sleep 1
# puts "not reached"

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

# Ruby的多线程不是真正的多线程,Ruby在处理IO的时候是没有GIL锁
# Jruby 可真正的实现多线程

mutex = Mutex.new

count1 = count2 = 0
difference = 0
counter = Thread.new do
  loop do
    mutex.synchronize do # 线程在执行这块block 这个线程不会被其他线程切换掉
        count1 += 1
        count2 += 2
      end
  end
end
spy = Thread.new do
  loop do
    mutex.synchronize do
        difference += (count1 - count2).abs
      end
  end
end
sleep 1
puts "count1 : #{count1}"
puts "count2 : #{count2}"
puts "difference : #{difference}"


 

转载于:https://my.oschina.net/u/3544267/blog/1576067

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值