writing price publisher using coop/threading models
--HG-- branch : sandbox
This commit is contained in:
86
src/circuits/primes.py
Normal file
86
src/circuits/primes.py
Normal file
@@ -0,0 +1,86 @@
|
||||
# Copyright 2010 baloan
|
||||
# See LICENSE for details.
|
||||
|
||||
''' multiprocessing demo '''
|
||||
|
||||
# system imports
|
||||
|
||||
from circuits import Component, Event, Timer, handler, Debugger
|
||||
from math import sqrt
|
||||
import logging
|
||||
|
||||
# globals
|
||||
|
||||
LOG = logging.getLogger()
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG,
|
||||
format='%(asctime)s.%(msecs)03d %(process)d:%(thread)d %(levelname).4s %(message)s',
|
||||
datefmt='%H:%M:%S')
|
||||
|
||||
# definitions
|
||||
|
||||
class Print(Event):
|
||||
'Print Event'
|
||||
|
||||
class Timeout(Event):
|
||||
'Timeout'
|
||||
|
||||
|
||||
class Input(Component):
|
||||
def started(self, component, mode):
|
||||
LOG.info('started %s %s', component, mode)
|
||||
for n in range(100):
|
||||
LOG.info('put %i', n)
|
||||
self.push(Event(n))
|
||||
LOG.info('worker done, ending')
|
||||
Timer(5, Timeout('msg'), "timeout").register(self)
|
||||
|
||||
def timeout(self, e):
|
||||
LOG.info("timeout %s", e)
|
||||
self.stop()
|
||||
|
||||
def stopped(self, e):
|
||||
pass
|
||||
|
||||
|
||||
class Filter(Component):
|
||||
def started(self, component, mode):
|
||||
LOG.info('started %s %s', component, mode)
|
||||
|
||||
def event(self, n):
|
||||
LOG.info('Filter:event %i', n)
|
||||
if self.is_prime(n):
|
||||
LOG.info('Filter: sending %i', n)
|
||||
self.push(Print(n))
|
||||
|
||||
def is_prime(self, n):
|
||||
if n < 2:
|
||||
return False
|
||||
if n in (2, 3):
|
||||
return True
|
||||
for i in range(2, int(sqrt(n)) + 1):
|
||||
if n % i == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class Output(Component):
|
||||
def started(self, component, mode):
|
||||
LOG.info('started %s %s', component, mode)
|
||||
|
||||
@handler('print')
|
||||
def onPrint(self, n):
|
||||
print '%i, ' % (n,),
|
||||
|
||||
|
||||
def runInline():
|
||||
master = Input()
|
||||
master += Filter()
|
||||
master += Output()
|
||||
master += Debugger()
|
||||
master.run()
|
||||
LOG.info('done.')
|
||||
|
||||
if __name__ == '__main__':
|
||||
runInline()
|
||||
|
||||
Reference in New Issue
Block a user