1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/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!'