Mutexes

There may be occasions when multiple threads each need to access some kind of global resource. This has the potential of producing erroneous results because the current state of the global resource may be modified by one thread and this modified value may be unpredictable when it is used by some other thread. For a simple example, look at this code:

no_mutex.rb

$i = 0

def addNum(aNum)
    aNum + 1
end

somethreads = (1..3).collect {
    Thread.new {
        1000000.times{ $i = addNum($i)  }
    }
}


somethreads.each{|t| t.join }
puts( $i )

My intention here is to create and run three threads, each of which increments the global variable, $i, 1 million times. I do this by enumerating from 1 to 3 and creating an array using the collect method (the map method is synonymous ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.