#!/usr/bin/ruby

require "mooix"
require "mooix/thing"

Mooix.run do
  # Set the duck to waddling. Note that this is done while
  # the duck is still (presumably) locked by the caller. Use
  # a unique id in the waddling field since this method might
  # be called twice at the same time.
  pid = Process.pid
  self.waddling = pid
  # After forking to the background, the duck isn't locked
  # for movement anymore (since the caller holds the lock
  # only until this method returns).
  Mooix.background do
    while self.spring > 0
      # Lock the duck for movement, then check to see if
      # it's still supposed to be waddling, or if
      # something stopped it.
      # Demonstrates the first broad category of getlock invocation.
      # Return a lock that can be closed at will.
      lock = self.getlock
      if self.waddling == pid
	# The duck is still waddling.
	msg("energetic_waddle")
	self.spring -= 1
	# Close the earlier lock.
	lock.close
	sleep(1)
      else
	# Something stopped the waddling.
	Mooix.return
      end # if self.waddling == pid
    end # while self.spring > 0
    # Stop waddling.
    # Other category of lock invocation.
    # self.getlock accepts an optional block.
    # All code within the block is run and the lock is closed.
    if self.waddling == pid
      self.getlock do
        msg("waddle")
          self.waddling = 0
      end # self.getlock do
    else
      Mooix.return
    end # if self.waddling == pid
  end # Mooix.background do
end # Mooix.run
