Wednesday, 15 July 2015

ruby - Class Variables and initialisation time -



ruby - Class Variables and initialisation time -

if create class variable so:

class song @@plays = 0 class << self def plays=( plays ) @@plays += plays end def plays @@plays end end end

an have multiple threads accessing class method , setting in jruby:

t1 = thread.new {st1 = song.plays = 1} t2 = thread.new {st2 = song.plays = 5} t3 = thread.new {st3 = song.plays = 3}

is possible have 2 threads initialise @@plays 0 @ same time? @ stage in execution class variables created?

@@plays = 0 set when ruby evaluates class definition. should happen 1 time , before starting threads.

the assignment method plays= on other hand can executed concurrently. should hence wrap in synchronize call, e.g.:

require 'thread' require 'song' # <- @@plays set 0 here song.plays #=> 0 semaphore = mutex.new t1 = thread.new { semaphore.synchronize { song.plays = 1 } } t2 = thread.new { semaphore.synchronize { song.plays = 5 } } t3 = thread.new { semaphore.synchronize { song.plays = 3 } } [t1, t2, t3].each(&:join) song.plays #=> 9

another alternative create song#plays= thread-safe moving mutex song class:

class song @@plays = 0 @@semaphore = mutex.new def self.plays=(plays) @@semaphore.synchronize { @@plays += plays } end # ... end

ruby thread-safety jruby

No comments:

Post a Comment