quabbinの日記: RubyのThread(2)
前回の続き。
currentのThreadが計測の邪魔をしている可能性が非情に高いと考え、currentのThreadのpriorityを最大にして、Thread生成の邪魔をしないよう、Mutexでlockしてみた。
require 'thread'
def create_thread(priority, count, data, m)
t = Thread.start{
while m.locked?
Thread.pass
end
while $share.size < count
$share.push data
end
}
t.priority = priority #=> ここでstop
t
end
def check(a, b)
$share = []
m = Mutex.new
m.lock
count = 100000
t1 = create_thread a, count, "a", m
t2 = create_thread b, count, "b", m
m.unlock
t1.join
t2.join
counter = Hash.new(0)
$share.each{|value|
counter[value] += 1
}
p [a, b, counter]
end
if __FILE__ == $0
Thread.current.priority = 2147483647
check 0, 0
check 0, 1
check 0, 10
check 0, 2147483647
check 1, 2
check -2147483648, 2147483647
check 2147483647, -2147483648
end
カウントする数も変化させたところ、下の結果となった
+-------------+-------------+---------+---------+
| A優先順位 | B優先順位 | A実行数 | B実行数 |
+-------------+-------------+---------+---------+
| 0 | 0 | 500001 | 500000 |
| 0 | 1 | 0 | 1000000 |
| 0 | 10 | 0 | 1000000 |
| 0 | 2147483647 | 0 | 1000000 |
| 1 | 2 | 0 | 1000000 |
| -2147483648 | 2147483647 | 0 | 1000000 |
| 2147483647 | -2147483648 | 1000000 | 0 |
+-------------+-------------+---------+---------+
どうやら、currentのThreadの影響は排除された。
Ruby Threadは、大きいか小さいかのみを考慮しており、1の違いは大きな実行数の違いになるという結果が出た。
優先順位の違いはもう少し滑らかかと思ったけど、結構極端に出る。
時分割方式はどうなっているのだろうか…今度、インタプリタのコードを読んでみよう。
RubyのThread(2) More ログイン