Ruby 多线程

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

分享
# 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}"

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台