2
首先我是Ruby newby,我正在努力學習這門語言。我知道學習的最好方式是真正解決問題。所以我把一個簡單的字符串問題並實現解決方法1這樣的:Ruby 1.9.3多線程實現比單個威脅實現需要更長的時間,爲什麼?
def similarities(str)
result = str.length
(1..str.length - 1).each { |start|
str2 = str[start..-1]
index = 0
str2.split(//).each do |c|
break if c != str[index, 1]
index += 1
end
result += index
}
result
end
然後,它發生,我認爲這是一個「平行的foreach」那種想起絕配。所以,我想出了溶液2
def similarities(str)
result = str.length
threads = []
(1..str.length - 1).each { |start|
str2 = str[start..-1]
threads << Thread.new { calculate(str, str2) }
}
threads.each { |t| t.join; result += t["index"] }
result
end
def calculate(str, str2)
index = 0
str2.split(//).each do |c|
break if c != str[index, 1]
index += 1
end
Thread.current["index"] = index
end
令我驚訝的溶液2了大約8倍以上的時間完全相同的輸入解決方法1運行。爲什麼?
感謝,