# list0704.rb
require 'thread'
mem = 0 # 共有変数
m = Mutex::new # 相互排除を管理するための変数m
t1 = Thread::fork{
1000.times{
m.synchronize{ # 共有変数への読み書きはクリティカルなので
x = mem # 相互排除の管理下で実行する。
sleep(0.01) # この区間をクリティカルセクションという
mem = x + 2
}
}
}
t2 = Thread::fork{
1000.times{
m.synchronize{
y = mem
sleep(0.01)
mem = y + 1
}
}
}
t1.join
t2.join
puts mem