Created
August 9, 2020 05:00
-
-
Save externvoid/0a43976f2d103aa30565d2e3476da46c to your computer and use it in GitHub Desktop.
rubyでMutex, Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 内積の計算を2Threadで実行。 | |
ary0 = [0.4, 0.2, 0.3, 0.5, 0.2, 0.4, 0.5, 0.1, 0.2, 0.4, 0.5, 0.9] | |
ary1 = [0.1, 0.2, 0.2, 0.2, 0.3, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.9] | |
sum = 0 | |
lock = Mutex.new | |
q = Queue.new | |
[{:from => 0, :to => ary0.size/2}, | |
{:from => ary0.size/2+1, :to => ary0.size-1}].each {|e| | |
q.push proc { | |
t = 0 | |
e[:from].upto(e[:to]) {|i| | |
t = t + ary0[i] * ary1[i] | |
} | |
lock.synchronize { sum = sum + t } | |
} | |
} | |
th = [] | |
0.upto(1) {|i| | |
th << Thread.new { | |
until q.empty? | |
q.pop.call | |
end | |
} | |
} | |
th.each {|t| t.join} | |
puts sum | |
# 2Threadで実行して得た結果と、1Threadで計算して得た結果を比較 | |
checksum = 0 | |
ary0.each_with_index {|e, i| | |
checksum = checksum + ary0[i] * ary1[i] | |
} | |
puts checksum | |
__END__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment