Ruby 多线程

栏目: 编程语言 · Ruby · 发布时间: 6年前

内容简介: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}"


 


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Types and Programming Languages

Types and Programming Languages

Benjamin C. Pierce / The MIT Press / 2002-2-1 / USD 95.00

A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors by classifying program phrases according to the kinds of values they compute. The study of typ......一起来看看 《Types and Programming Languages》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具