Behaviour of Thread#stop?

Hello dear Fellow Rubyists !
I’m currently struggling with Ruby threads, especially the #stop and
#stop? methods. My program has two threads:

  • a worker performing tasks and ultimately calling Thread.stop (it is
    supposed to do so before to be allowed to continue)
  • a monitor asking for the status of the worker thread and waiting
    until it has reached the call to Thread.stop

I thought that Thread#stop? would be the way to go for the monitor
thread, but it doesn’t seem to do what I want. It doesn’t work with
1.9, but seems to work with 1.8, which is quite confusing.

The piece of code trying to wake the worker up as follow:
while !thr.stop?()
Thread.pass()
end
thr.wakeup()

Unfortunately, thr.stop?() never returns false, so I’m basically
trying to wake a thread that is not sleeping !

TIA ! :slight_smile:

“Xavier Noëlle” [email protected] wrote in post #968343:

I’m currently struggling with Ruby threads, especially the #stop and
#stop? methods.

You probably don’t want to be doing this. There are higher-level data
structures which will more likely do what you want.

For example, look at the Queue class. Your worker(s) can pop a message
from the queue as its instructions to work. It works happily with
multiple workers popping from the same queue, as they’ll take it in
turns to pop.

Look also at ConditionVariable.

Note you need to require ‘thread’ for both Queue and ConditionVariable.

Also, I saw a simple Semaphore class posted a long time ago, which isn’t
in the standard library, but you can just copy-paste it.

thr.stop? returns true not only when thr is dead but also when it is
sleeping. Moreover, if thr gets blocked outside by the global
interpreter lock (i.e. not executing at the moment), then thr will also
be put into a `sleep’ state, and thus thr.stop? will return false.

In your case, the tasks seem to be naturally cooperative, so a fiber is
preferred to a thread.

2010/12/14 Brian C. [email protected]:

You probably don’t want to be doing this. There are higher-level data
structures which will more likely do what you want.

For example, look at the Queue class. Your worker(s) can pop a message
from the queue as its instructions to work. It works happily with
multiple workers popping from the same queue, as they’ll take it in
turns to pop.

You’re absolutely right. I forgot about the Queue structure, which is
perfect for my needs !

Also, I saw a simple Semaphore class posted a long time ago, which isn’t
in the standard library, but you can just copy-paste it.

I’ll take a look at that. It would be nice if it was in the standard
library !

@Su Zhang: I tried with a dummy loop (in fact, there is no code
between the mutex release and Thread.stop(), so I needed to cheat) and
#stop? returns false even when not sleeping. What do you mean by
“blocked outside by the GIL” (I know what the GIL is, but don’t
understand what kind of problem you’re talking about in this
sentence).