Debian Codegraph @

futurist/_thread.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import atexit
14 import queue
15 import threading
16 import weakref
17
18
19 class Threading:
20
21 @staticmethod
22 def event_object(*args, **kwargs):
23 return threading.Event(*args, **kwargs)
24
25 @staticmethod
26 def lock_object(*args, **kwargs):
27 return threading.Lock(*args, **kwargs)
28
29 @staticmethod
30 def rlock_object(*args, **kwargs):
31 return threading.RLock(*args, **kwargs)
32
33 @staticmethod
34 def condition_object(*args, **kwargs):
35 return threading.Condition(*args, **kwargs)
36
37
38 _to_be_cleaned = weakref.WeakKeyDictionary()
39 _dying = False
40
41
42 class _Stopping(Exception):
43 pass
44
45
46 class ThreadWorker(threading.Thread):
47 MAX_IDLE_FOR = 1
48
49 def __init__(self, executor, work_queue):
50 super().__init__()
51 self.work_queue = work_queue
52 self.should_stop = False
53 self.idle = False
54 self.daemon = True
55 # Ensure that when the owning executor gets cleaned up that these
56 # threads also get shutdown (if they were not already shutdown).
57 self.executor_ref = weakref.ref(executor, lambda _obj: self.stop())
58
59 @classmethod
60 def create_and_register(cls, executor, work_queue):
61 w = cls(executor, work_queue)
62 # Ensure that on shutdown, if threads still exist that we get
63 # around to cleaning them up and waiting for them to correctly stop.
64 #
65 # TODO(harlowja): use a weakrefset in the future, as we don't
66 # really care about the values...
67 _to_be_cleaned[w] = True
68 return w
69
70 def _is_dying(self):
71 if self.should_stop or _dying:
72 return True
73 executor = self.executor_ref()
74 if executor is None:
75 return True
76 # Avoid confusing the GC with cycles (since each executor
77 # references its known workers)...
78 del executor
79 return False
80
81 def _wait_for_work(self):
82 self.idle = True
83 work = None
84 while work is None:
85 try:
86 work = self.work_queue.get(True, self.MAX_IDLE_FOR)
87 except queue.Empty:
88 if self._is_dying():
89 raise _Stopping()
90 self.idle = False
91 return work
92
93 def stop(self):
94 self.should_stop = True
95
96 def run(self):
97 while not self._is_dying():
98 try:
99 work = self._wait_for_work()
100 except _Stopping:
101 return
102
103 try:
104 work.run()
105 finally:
106 # Mark task as done for queue.join() support
107 self.work_queue.task_done()
108 # Avoid any potential (self) references to the work item
109 # in tracebacks or similar...
110 del work
111
112
113 def _clean_up():
114 """Ensure all threads that were created were destroyed cleanly."""
115 global _dying
116 _dying = True
117 threads_to_wait_for = []
118 while _to_be_cleaned:
119 worker, _work_val = _to_be_cleaned.popitem()
120 worker.stop()
121 threads_to_wait_for.append(worker)
122 while threads_to_wait_for:
123 worker = threads_to_wait_for.pop()
124 try:
125 worker.join()
126 finally:
127 del worker
128
129
130 atexit.register(_clean_up)