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}"


 


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

查看所有标签

猜你喜欢:

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

The Art of Computer Programming, Volume 2

The Art of Computer Programming, Volume 2

Knuth, Donald E. / Addison-Wesley Professional / 1997-11-04 / USD 79.99

Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 2》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具