News for hackers. Stuff that matters.
Re:Ruby core classes aren't thread safe by incidently on Monday February 25, 2013 @04:24PM (#5281907)
The article seems to be wrong in several aspects ... First, the issue described has nothing to do with arrays; the same problem happens when using a plain number:

    class Inventory
      def initialize(nb)
        @nb_items = nb
      end
     
      def decrease
        @nb_items -= 1
      end
     
      def nb_items
        @nb_items
      end
    end 

    @inventory = Inventory.new(4000) 


    threads = Array.new
    400.times do
      threads << Thread.new do
        10.times do
          @inventory.decrease
        end
      end
    end
     
    threads.each(&:join)
    puts @inventory.nb_items
Second, the mutex in the OP's code synchronizes the whole block passed to a thread, i.e. there's no parallelism at all (the second thread waits until the first one finishes, and so on). It should rather be something like:

    class Inventory
      def initialize(nb)
        @nb_items = nb

        @lock = Mutex.new
      end
     
      def decrease
        @lock.synchronize do
          @nb_items -= 1
        end
      end
     
      def nb_items
        @nb_items
      end
    end 

    @inventory = Inventory.new(4000) 

    threads = Array.new

    400.times do
      threads << Thread.new do
        10.times do
          @inventory.decrease
        end
      end
    end
     
    threads.each(&:join)
    puts @inventory.nb_items

There are no comments on this comment yet.