-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeeder.py
72 lines (50 loc) · 1.68 KB
/
feeder.py
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
64
65
66
67
68
69
70
71
72
# -*- coding:utf-8 -*-
import time
import threading
class Feeder(threading.Thread):
__buff=[]
buff_size=1000
def __init__(self,filename):
threading.Thread.__init__(self)
self.__condition=threading.Condition()
self.__buff_lock=threading.Lock()
self.__fp=open(filename,'r')
self.daemon=True
def run(self):
while True:
#producer acquire condition
self.__condition.acquire()
print "feeder acquire condition"
while len(self.__buff) < self.buff_size:
line=self.__fp.readline()
if line!='':
#acquire buff
self.__buff_lock.acquire()
#print "feeder acquire buff lock"
self.__buff.append(line)
#release buff
self.__buff_lock.release()
print "feed got",line
#notify condition
self.__condition.notify()
#print "feeder notify condition"
continue
#if nothing , go to sleep
break
#release
self.__condition.release()
print "feeder release condition"
time.sleep(5)
def get_one(self):
self.__buff_lock.acquire()
if self.__buff==[]:
return None
line=self.__buff.pop(0)
self.__buff_lock.release()
return self.__handle(line)
def get_condition(self):
return self.__condition
def __handle(self,line):
if line[-1]== '\n':
line=line[:-1]
return line