-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmythreading.py
60 lines (44 loc) · 1.56 KB
/
mythreading.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
from threading import Thread
from threading import Event
from multiprocessing import Queue
from Queue import Empty
import socket
import logging
class MyThread(Thread):
STOP_TIMEOUT_SECS=3.0
def __init__(self,processing_function):
super(MyThread, self).__init__()
self._processing_function=processing_function
self._stop = Event()
def stop(self):
self._stop.set()
def stopping(self):
return self._stop.is_set()
class ReceiveQueueThread(MyThread):
def __init__(self,processing_function,queue):
super(ReceiveQueueThread,self).__init__(processing_function)
self._queue = queue
def run(self):
while not self.stopping():
try:
s = self._queue.get(block=True, timeout=self.STOP_TIMEOUT_SECS)
except Empty:
continue
if not self.stopping():
self._processing_function(s)
class ReceiveSocketThread(MyThread):
def __init__(self,processing_function,connection):
super(ReceiveSocketThread,self).__init__(processing_function)
self._connection = connection
def run(self):
#TODO: set connection timeout ?
while not self.stopping():
data = self._connection.recv(1024)
if not data:
break
if not self.stopping():
self._processing_function(data)
def main():
pass
if __name__ == '__main__':
main()