When I first discovered the threads, I tried to verify that they actually worked as expected by invoking sleep in many threads, depending on normal sleep. It worked and I was very happy.
But then my friend told me that these flows were not really parallel, and this dream was supposed to pretend.
So now I wrote this test to do the actual processing:
class Test ITERATIONS = 1000 def run_threads start = Time.now t1 = Thread.new do do_iterations end t2 = Thread.new do do_iterations end t3 = Thread.new do do_iterations end t4 = Thread.new do do_iterations end t1.join t2.join t3.join t4.join puts Time.now - start end def run_normal start = Time.now do_iterations do_iterations do_iterations do_iterations puts Time.now - start end def do_iterations 1.upto ITERATIONS do |i| 999.downto(1).inject(:*)
And now I am very sad because run_threads () not only does not work better than run_normal, but even slower!
Then why should I complicate my application with threads if they are not parallel?
** UPDATE **
@ fl00r said that I could use streams if I used them for I / O, so I wrote two more do_iterations:
def do_iterations # filesystem IO 1.upto ITERATIONS do |i| 5.times do # create file content = "some content #{i}" file_name = "#{Rails.root}/tmp/do-iterations-#{UUIDTools::UUID.timestamp_create.hexdigest}" file = ::File.new file_name, 'w' file.write content file.close # read and delete file file = ::File.new file_name, 'r' content = file.read file.close ::File.delete file_name end end end def do_iterations # MongoDB IO (through MongoID) 1.upto ITERATIONS do |i| TestModel.create! :name => "some-name-#{i}" end TestModel.delete_all end
The performance results are the same: normal> threads.
But now I'm not sure if my VM can use all the cores. Will be back when I checked this.
source share