#!/usr/bin/env python
import threading as t
import Queue as q
import random as r
import time
class GrabData(t.Thread):
"This object retrieves/generates data and puts it onto a Queue"
abortevent = t.Event()
def run(self):
while not GrabData.abortevent.isSet():
dataqueue.put(r.randint(0,100))
time.sleep(1e-3*r.randint(500,1500))
class DropData(t.Thread):
"This object does manipulate the data, but simple stores it in a file."
filelock = t.Lock()
def __init__(self,file):
t.Thread.__init__(self)
self.file = file
def run(self):
while True:
if GrabData.abortevent.isSet() and dataqueue.empty():
break
try:
data = dataqueue.get(timeout=1)
except:
continue
else:
DropData.filelock.acquire()
file = open(self.file,'a')
file.write(str(data)+'\n')
file.close()
DropData.filelock.release()
dataqueue = q.Queue()
for i in range(5):
grabber = GrabData()
grabber.daemon = True
grabber.start()
dropper = DropData('output.dat')
dropper.daemon = True
dropper.start()
print "Hit 'Ctrl'+'C' or 'Ctrl'+'D' to quit"
try:
while True:
pass
except:
GrabData.abortevent.set()
while t.activeCount() > 1:
time.sleep(.1)
print 'GOODBYE!'