Skip to content

Instantly share code, notes, and snippets.

@laclefyoshi
Created February 26, 2011 03:03
Show Gist options
  • Save laclefyoshi/844894 to your computer and use it in GitHub Desktop.
Save laclefyoshi/844894 to your computer and use it in GitHub Desktop.
Jython and STM/Agent (Akka)
#!/usr/bin/jython
# -*- coding: utf-8 -*-
# Copyright : (c) SAEKI Yoshiyasu
# License : MIT-style license
# <http://www.opensource.org/licenses/mit-license.php>
# last updated: 2011/02/26
from akka.stm import Atomic, Ref
import time
# create ref object
r = Ref(0)
class A(Atomic):
def atomically(self):
inc = r.get() + 1
r.set(inc)
return inc
# create 2 atomic instances
# these instances refer a same ref object
aa = A()
bb = A()
def count(atom):
# call atomically method of atomic instance
return atom.execute()
for i in range(5):
print "STM1> ", count(aa)
for i in range(5):
print "STM2> ", count(bb)
###
from akka.agent import Agent
from akka.japi import Function, Procedure
# create agent object having ref object (2)
a = Agent(2)
# get ref object of agent
print "agent> ",
print a.get()
# update ref object of agent
a.send(8)
time.sleep(1)
print "agent send()> ",
print a.get()
class F(Function):
def apply(self, n):
return n * 2
# apply function to ref object of agent
a.send(F())
time.sleep(1)
print "agent send(f)> ",
print a.get()
# apply function to ref object of agent with blocking
a.sendOff(F())
time.sleep(1)
print "agent sendOff> ",
print a.get()
# return new agent generated existing agent and function
b = a.map(F())
time.sleep(1)
print "agent map> ",
print b.get()
class P(Procedure):
def apply(self, n):
# similar to Function but no return
print n * 3
# apply function to ref object of agent
print "agent foreach> ",
a.foreach(P())
a.close()
b.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment