-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfuture1.py
More file actions
242 lines (172 loc) · 5.7 KB
/
future1.py
File metadata and controls
242 lines (172 loc) · 5.7 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# coding: utf-8
# In[11]:
import threading
import time
# Future states:
#
# An instance of the future could be in any of these states.
# 1. PENDING : The future does not have the result/exception for the corresponding work.
# 2. RUNNING : TBD
# 3. CANCELLED : The future got cancelled before the result of the associated work was computed.
# 4. FINISHED : The associated work got finished and resulted in giving out a value or exception.
# In[12]:
PENDING = 'pending'
RUNNING = 'running'
CANCELLED = 'cancelled'
FINISHED = 'finished'
FUTURE_STATES = [
PENDING,
RUNNING,
CANCELLED,
FINISHED
]
# In[13]:
class FutureCancelledError(Exception):
""""""
def __init__(self):
pass
class FutureTimeoutError(Exception):
""""""
def __init__(self):
pass
# In[14]:
class Future(object):
def __init__(self):
""""""
self._state = PENDING
self._condition = threading.Condition()
self._done_callbacks = []
self._result = None
self._exception = None
def add_done_callback(self, cb):
"""
Add the callback to be executed when the future state becomes
cancelled/finished
"""
with self._condition:
if self._state not in [CANCELLED, FINISHED]:
self._done_callbacks.append(cb)
return
#Call immediately if result/exception already set
cb(self)
def result(self, timeout=None):
"""
Blocking call on the calling thread.
timeout: time to wait for the result to be ready.
Throws:
FutureCancelledError if the state of future was CANCELLED
or became CANCELLED later.
FutureTimeoutError if future did not become ready before
the timeout.
"""
with self._condition:
if self._state in [CANCELLED]:
raise FutureCancelledError()
if self._state == FINISHED:
# Already done, return the result
return self._result
self._condition.wait(timeout)
if self._state in [CANCELLED]:
raise FutureCancelledError()
if self._state == FINISHED:
return self._result
else:
return FutureTimeoutError()
pass
def exception(self, timeout=None):
"""
Blocking call on the calling thread.
"""
with self._condition:
if self._state in [CANCELLED]:
raise FutureCancelledError()
if self._state == FINISHED:
#Already done. Return the exception
return self._exception
self._condition.wait(timeout)
if self._state in [CANCELLED]:
raise FutureCancelledError()
if self._state == FINISHED:
return self._exception
else:
raise FutureTimeoutError()
def done(self):
"""Future is finished"""
with self._condition:
return self._state in [CANCELLED, FINISHED]
def cancelled(self):
""" Is the future cancelled or not"""
with self._condition:
return self._state == CANCELLED
def cancel(self):
"""Cancel the future if not already finished or running"""
with self._condition:
if self._state in [RUNNING, FINISHED]:
return False
self._set_state(CANCELLED)
self._condition.notify_all()
self._execute_done_callbacks()
return True
def set_result(self, result):
"""
Sets the result of the work associated with this future.
"""
with self._condition:
self._result = result
self._state = FINISHED
self._condition.notify_all()
self._execute_done_callbacks()
def set_exception(self, exp):
"""
Sets the exception that occurred while performing
the work associated with this future.
"""
with self._condition:
self._exception = exp
self._state = FINISHED
self._condition.notify_all()
self._execute_done_callbacks()
def _set_state(self, state):
"""
Sets the state.
Assumes that lock is taken
"""
self._state = state
def _execute_done_callbacks(self):
for cb in self._done_callbacks:
try:
cb(self)
except Exception as e:
print ("ERROR: {}".format(str(e)))
def __iter__(self):
"""
This future is an iterable now.
"""
if not self.done():
yield self
return self.result()
# Lets write some tests to check our future in action
# In[15]:
def bg_task():
print ("Background task started")
time.sleep(10)
print ("Background task finished")
return 42
# In[16]:
class ThreadedExecutor(object):
def __init__(self):
self._thread = threading.Thread(target=self._runner)
def submit(self, task, *args, **kwargs):
""""""
f = Future()
t = threading.Thread(target=self._runner, args=(f, task, args, kwargs,))
t.start()
return f
def _runner(self, fut, task, args, kwargs):
v = task(*args, **kwargs)
fut.set_result(v)
pass
# In[17]:
if __name__ == "__main__":
f = ThreadedExecutor().submit(bg_task)
f.result()