# Ruby 多线程

2017-11-22 14:17:26来源:oschina作者:穿山人点击

# 创建线程之后线程会执行代码块中的东西
# 像处理图片的话计算机CPU计算较多称为Compute-bound 上传下载的话是IO-bound
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
count = 0
arr= []
10.times do |i|
sleep(rand(0)/10.0)
count += 1
end
end
arr.each do |t|
t.join
print t["count"], ","
end
puts "count = #{count}"
# 线程的优先 priority 的值越大 越优先
count1 = count2 = 0
loop { count1 += 1}
end
a.priority = 1
loop { count2 += 1}
end
b.priority = -1
sleep 1
p count1
p count2
# 如果主线程再等待子线程 如果此时子线程发生异常则会上抛给主线程
# end
# t1.join
# puts "not reached"
# 但如果主线程不等待的话 子线程就自己终止掉
# end
# sleep 1
# puts "not reached"
#
# end
# sleep 1
# puts "not reached"
# Mutex
# count1 = count2 = 0
# difference = 0
# loop do
# count1 += 1
# count2 += 2
# end
# end
# 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
loop do
mutex.synchronize do # 线程在执行这块block 这个线程不会被其他线程切换掉
count1 += 1
count2 += 2
end
end
end
loop do
mutex.synchronize do
difference += (count1 - count2).abs
end
end
end
sleep 1
puts "count1 : #{count1}"
puts "count2 : #{count2}"
puts "difference : #{difference}"