Skip to content

Instantly share code, notes, and snippets.

@jyfeather
Created June 27, 2013 11:17
Show Gist options
  • Save jyfeather/5875701 to your computer and use it in GitHub Desktop.
Save jyfeather/5875701 to your computer and use it in GitHub Desktop.
--> started at 2013-06-27 19:14:48 +0800
counter1 : 367240
counter2 : 367240
difference : 0
--> end at 2013-06-27 19:14:49 +0800
#!/usr/bin/ruby
require 'thread'
mutex = Mutex.new # 生成锁对象
counter1 = counter2 = 0
difference = 0
puts "--> started at #{Time.now}"
t1 = Thread.new do # new/start/fork是alias的方法,基本功能相同。
loop do
mutex.synchronize do # 同步锁
counter1 += 1
counter2 += 1
end
end
end
t2 = Thread.new do
loop do
mutex.synchronize do # 同步锁,控制读写
difference += (counter1 - counter2).abs
end
end
end
sleep 1
puts "counter1 : #{counter1}"
puts "counter2 : #{counter2}"
puts "difference : #{difference}"
#t1.join # 阻塞当前线程,当t1线程运行结束后,阻塞线程重新进入运行状态。相当于将线程同步执行
#t2.join
puts "--> end at #{Time.now}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment