Agentes en AjSharp (Parte 2)

Published on Author lopezLeave a comment

Estuve implementando una especie de soporte de agentes en mi intérprete AjSharp. En el anterior post:

Agents in AjSharp (Part 1)
Agentes en AjSharp (Parte 1)

describí algo de esa implementación y las principales características. Dos puntos para recordar:

– Cada agente ejecuta en su propio thread
– Cada agente tiene una cola de proceso para recibir sus invocaciones (método y argumentos)

Quiero mostrar en este post dos simples ejemplos de uso. Primero, uno donde los agentes se encadenan, implementando algo así como message passing, procesando un dato y produciendo resultados.

agent IncrementAgent 
{
  function IncrementAgent(next, channel)
  {
    this.channel = channel;
    this.next = next;
  }
  
  sub Process(value)
  {
    newvalue = value + 1;
    
    if (channel)
      channel <- newvalue;
      
    if (next)
      next.Process(newvalue);
  }
}
channel = new Channel();
thirdAgent = new IncrementAgent(null, channel);
secondAgent = new IncrementAgent(thirdAgent, channel);
firstAgent = new IncrementAgent(secondAgent, channel);
firstAgent.Process(0);
for (k = 1; k <= 3; k++)
  result = result + <-channel; 
// result == 1 + 2 + 3 == 6

Vean que cada agente es un eslabon de la cadena de proceso, y que se usa un channel para coleccionar los resultados. La combinación de colaboración de objetos se puede hacer en formas más complejas.

En el segundo ejemplo, implementé el problema de Collatz usando una ronda de dos agentes:

if (number % 2)
    {
      this.Next.Process(number, list);
      return;
    }
    
    list.Add(number);
  
    number = number / 2;
    
    this.Next.Process(number, list);
  }
}
agent OddAgent 
{
  sub Process(number, list)
  {
    if ((number % 2)==0)
    {
      this.Next.Process(number, list);
      return;
    }
    
    list.Add(number);
    
    if (number == 1) 
    {
      this.Channel <- list;
      return;
    }
    
    number = number * 3 + 1;
    
    this.Next.Process(number, list);
  }
}
channel = new Channel();
even = new EvenAgent();
odd = new OddAgent();
even.Channel = channel;
even.Next = odd;
odd.Channel = channel;
odd.Next = even;
even.Process(22, new List());
result = <-channel;
// result = { 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 }

Más sobre la interesante conjetura de Collatz:

Collatz 3n+1 Problem Structure

Programming 3n+1 problem

Estos son ejemplos simples. Quiero implementar un web crawler, o un web scraping, o un algoritmo genético en paralelo, usando agentes. También tengo como próximo paso: agentes distribuidos.

Nos leemos!

Angel “Java” Lopez

http://www.ajlopez.com

http://twitter.com/ajlopez

Leave a Reply

Your email address will not be published. Required fields are marked *