Skip to content

Instantly share code, notes, and snippets.

@externvoid
Created August 9, 2020 05:00
Show Gist options
  • Save externvoid/0a43976f2d103aa30565d2e3476da46c to your computer and use it in GitHub Desktop.
Save externvoid/0a43976f2d103aa30565d2e3476da46c to your computer and use it in GitHub Desktop.
rubyでMutex, Queue
# 内積の計算を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