Wait for another thread to _initialize_
It looks like I miss something, but I canft accomplish the rather
standard task. I have two threads, one gdaemonh and one gclienth. The
daemon may be initializing for a while and than it listens for client. The
interaction is done using mutices:
#!/usr/bin/ruby
require 'rubygems'
require 'thread'
class TestThr
attr_reader :thread
# Client method to be called from outside.
# It will tug at daemonfs sleeve, forcing daemon to do smth
def touch
Thread.new {
@mutex.synchronize {
puts "Ë touch before in #{Thread.current}"
@cv.signal
puts "Ë touch after in #{Thread.current}"
}
}.join
end
# Daemon initialization. It is to be put into singleton instance,
# but at the moment the code is cleared out to show the case.
def initialize
@mutex = Mutex.new
@cv = ConditionVariable.new
@thread = Thread.fork {
sleep 1 # ⇐ LONG operation took place here
loop do
@mutex.synchronize {
puts "¨ got before in #{Thread.current}"
@cv.wait(@mutex)
puts "¨ got after in #{Thread.current}"
}
end
}
# UGLY UGLY UGLY
# sleep 3
end
end
t = TestThr.new # ⇐ A daemon run
2.times { t.touch } # ⇐ Knock-knock, Neo
The problem is that the daemon thread is not yet ready to be touched when
the calls to touch are being performed:
$ ruby testthr.rb
Ë touch before in #<Thread:0x00000001a1ded8>
Ë touch after in #<Thread:0x00000001a1ded8>
Ë touch before in #<Thread:0x00000001873c40>
Ë touch after in #<Thread:0x00000001873c40>
$
Of course, if I uncomment the ugly sleep 3 call in daemon initialization,
all will be fine (as well as if no long initialization (shown with sleep 1
in my example) took place:
$ ruby testthr.rb
¨ got before in #<Thread:0x000000023060b8>
Ë touch before in #<Thread:0x00000002305348>
Ë touch after in #<Thread:0x00000002305348>
¨ got after in #<Thread:0x000000023060b8>
¨ got before in #<Thread:0x000000023060b8>
Ë touch before in #<Thread:0x0000000215bba0>
Ë touch after in #<Thread:0x0000000215bba0>
¨ got after in #<Thread:0x000000023060b8>
$
But thatfs definitely not the best way to accomplish my task. Neither
#status nor #wakeup company doesnft fit in that case.
So, what am I doing wrong?
No comments:
Post a Comment