Archive for the tag 'pattern'

Pattern: Shutdown Flag

Problem: An agent should consider a shutdown flag presence.

Solution: The solution is to use a modified Boolean Flag Pattern, where the flag specific operation is to break the loop for reading an n-tuple, i.e. the Agent Life Cycle pattern.

(life cycle, boolean flag and shutdown flag patterns)

loop do
  begin
    read or take n-tuple with timeout t1
  rescue Rinda::RequestExpiredError

    begin
      read the shutdown flag with timeout t2
      break # stop listening for the n-tuple
    rescue Rinda::RequestExpiredError
      # ignore a situation when there is no shutdown flag
    end

    next # repeat the loop

  end
  process n-tuple
end

Example:

(life cycle, boolean flag and shutdown flag patterns)

loop do
  begin
    t = ts.take [:plus, nil, nil], 10
  rescue Rinda::RequestExpiredError

    begin
      ts.read [:end], 1
      break # stop listening for the n-tuple
    rescue Rinda::RequestExpiredError
      # ignore a situation when there is no shutdown flag
    end

    next # repeat the loop

  end
  res = t[1] + t[2]
  ts.write [:result, res]
end

Pattern: Boolean Flag

Problem: An agent should consider a flag presence.

Solution: The solution is to set a timeout for a read or take operation, where the timeout value specifies how often a flag appearance should be checked, and if the flag is presented to perform the flag specific operation.

The Agent Life Cycle pattern is, of course, used too.

(life cycle and boolean flag patterns)

loop do
  begin
    read or take n-tuple with timeout t1
  rescue Rinda::RequestExpiredError

    begin
      read the flag n-tuple with timeout t2
      perform a flag specific operation
    rescue Rinda::RequestExpiredError
      perform an operation when the flag is not set
    end

    next # repeat the loop

  end
  process n-tuple
end

Pattern: Agent Life Cycle

Problem: An agent should be able to check the blackboard for an n-tuple and to process the obtained n-tuple. (It is a trivial pattern.)

Solution: The solution is to perform operation read or take in a loop.

loop do
  read or take n-tuple

  process n-tuple
end

Example:

loop do
  t = ts.take [:plus, nil, nil]

  res = t[1] + t[2]
  ts.write [:result, res]
end

Comments:
The method process should execute agent’s duty :), there is only questionable, if it should:

  • start a new thread, to process the loaded n-tuple, and immediately listen for a next n-tuple
  • or it should process the loaded n-tuple, and when the processing is finished, to start listening for a next n-tuple.

I would prefer the second way - it is more agent-like, it is not mixing threads and agents concepts (including managing agents vs managing threads) - if you would like to process more n-tuples in parallel, simply start another agent instance.