Adding MonitorMixin causes compile failure when initialize takes a parameter

S

Scott

Hi, I am a relative newbie in Ruby and I need to do some simple thread
based programs.
In the new pickaxe book I saw this code for enabling a synchronized
block using a MonitorMixin

require 'monitor'

class Counter
include MonitorMixin
attr_reader :count
def initialize
@count = 0
super
end
def tick
synchronize do
@count += 1
end
puts @count
end
end

c = Counter.new
t1 = Thread.new{10000.times {c.tick} }
t2 = Thread.new{10000.times {c.tick} }
t1.join; t2.join

This works fine, except that in my application the class takes a
parameter, so I added a parameter to the new call and a parameter to
the initialize method as below,

require 'monitor'

class Counter
include MonitorMixin
attr_reader :count
def initialize(init_param)
@count = init_param
super
end
def tick
synchronize do
@count += 1
end
puts @count
end
end

c = Counter.new(2)
t1 = Thread.new{10000.times {c.tick} }
t2 = Thread.new{10000.times {c.tick} }
t1.join; t2.join

And when I do it fails to compile with the following error.
`initialize': wrong number of arguments (1 for 0) (ArgumentError)

What am I doing wrong?

Thanks for you r help with this

Scott
 
T

ts

Write it like this

S> def initialize(init_param)
S> @count = init_param
S> super

super() # call super without argument

S> end


Guy Decoux
 
A

ara.t.howard

Hi, I am a relative newbie in Ruby and I need to do some simple thread
based programs.
In the new pickaxe book I saw this code for enabling a synchronized
block using a MonitorMixin

require 'monitor'

class Counter
include MonitorMixin
attr_reader :count
def initialize
@count = 0
super
^^^^^
^^^^^
this implies super(*anyargs, &anyblock)

to call with zero args use 'super()'

-a
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top