On Fri, May 13, 2011 at 9:33 AM, Zd Yu <zdyu2000 / gmail.com> wrote:
> How to make two threads do something in turn, i.e., A =3D> B =3D> A =3D> =
B
> ....?
>
> I know the code below is not correct, but I do not know how to make it
> correct. Could anybody help?
>
> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
> mutex=3DMutex.new
>
> t=3DThread.new {
> =A0while true
> =A0 =A0Thread.stop
> =A0 =A0puts "B move..."
> =A0 =A0Thread.main.wakeup
> =A0end
> }
>
> while true
> =A0puts "A move..."
> =A0t.wakeup
> =A0Thread.stop
> end

Since you want to have one thread active at a time only this is not a
case for threads.  If at all you might use Fibers:

http://www.rubyinside.com/ruby-fibers-8-useful-reads-on-rubys-new-concurren=
cy-feature-1769.html
http://www.ruby-doc.org/core-1.9/classes/Fiber.html

The simplest solution is to code interchanges directly:

Actor =3D Struct.new :number do
  def alive?; rand(10) !=3D 0 end

  def step
    printf "Actor %p working...\n", number
  end
end

acts =3D Array.new(2) {|i| Actor.new i }

until acts.empty?
  acts.delete_if do |a|
    a.step
    !a.alive?
  end
end

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/