-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.py
More file actions
282 lines (210 loc) · 7.71 KB
/
examples.py
File metadata and controls
282 lines (210 loc) · 7.71 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# Examples demonstrating the usage of Threadify.
#
# David Smith
# 3/12/21
import time
from threadify import Threadify
import queue
def task_dots(storage):
"""
Task that prints dots forever.
"""
print(".", sep=" ", end="", flush=True)
time.sleep(.25)
return True
def task_symbols(storage):
"""
Task that prints first character of contents of storage["symbol"] forever.
"""
sym = storage.get("symbol", ".")
print(sym[0], sep=" ", end="", flush=True)
time.sleep(.25)
return True
def task_storage(storage):
"""
Demonstrates a periodic task accessing and modifying storage.
"""
# Values in storage persist from call to call. Local variables do not
# In case storage values haven't been passed in, set defaults
storage.setdefault("a", 1)
storage.setdefault("b", "A")
# Do work
print(storage)
# Operate on storage
storage["a"] += 1
# Fetch from storage, operate
tmp = storage["b"]
tmp = chr((ord(tmp) - ord("A") + 1) % 26 + ord("A"))
# Update storage
# Note: for value to persist, it must be assigned back to storage
storage["b"] = tmp
# Sleep allows other threads to run
time.sleep(1)
return True
def task_run_5s(storage):
"""
Demonstrates self-terminating task.
Use storage to pass in a start time so that task can decide when to self-terminate.
"""
# Get start time from storage
start = storage.get("start_time")
# Compute elapsed time and print
delta = time.time() - start
print("Elapsed time: {:4.2f}".format(delta))
# Time to die?
if delta >= 5:
print("Stopping after {:4.2f} seconds".format(delta))
# Signal thread to terminate
return False
# Sleep allows other threads to run
time.sleep(0.5)
# Signal thread to keep running
return True
def exception_task(storage):
# Get start time from storage
start = storage.get("start_time")
# Compute elapsed time and print
delta = time.time() - start
print("Elapsed time: {:4.2f}".format(delta))
# Sleep allows other threads to run
time.sleep(1)
# Time to kill?
if delta >= 5:
print("Raising exception after {:4.2f} seconds".format(delta))
# Signal thread to terminate
raise Exception("Exception thrown from task!")
# Signal thread to keep running
return True
def task_checkqueue(storage):
"""
Task that watches a queue for messages and acts on them when received.
"""
# Get the queue object from the storage dictionary
thequeue = storage.get("queue")
try:
# Use a timeout so it blocks for at-most 0.5 seconds while waiting for a message. Smaller values can be used to
# increase the cycling of the task and responsiveness to Threadify control signals (like pause) if desired.
msg = thequeue.get(block=True, timeout=.5)
except queue.Empty:
print("_", end="")
else:
if msg == "QUIT":
return False
# Print received message
print("{:s}".format(msg), end="")
return True
def task_dosomething(storage):
"""
Task that gets launched to handle something in the background until it is completed and then terminates. Note that
this task doesn't return until it is finished, so it won't be listening for Threadify pause or kill requests.
"""
# An important task that we want to run in the background.
for i in range(10):
print(i, end="")
time.sleep(1)
return False
# Sequentially run through a series of examples
if __name__ == "__main__":
# Enable debug outputs
Threadify.ENABLE_DEBUG_OUTPUT = True
# ** EXAMPLE 1) Simplest example - built-in task displays '.' to the screen each 0.25 seconds. **
print("\nEX 1) Print '.' approximately every 0.25 seconds.")
t1 = Threadify(start=True)
# Main program sleeps here while task continues to run
time.sleep(5)
# Send kill request and wait for it to complete
t1.kill(wait_until_dead=True)
print("Done")
# ** EXAMPLE 2) Demonstrate two tasks running with one being paused and later continued. **
print("\nEX 2) Starting 2 tasks - one will be paused and later continued while the first runs continuously.")
# Pass initial value of "symbol" via the storage dictionary to each task
t1 = Threadify(task_symbols, {"symbol": "X"})
t2 = Threadify(task_symbols, {"symbol": "O"})
# Start tasks manually (could also have been automatically started by using the start parameter)
t1.start()
t2.start()
time.sleep(5.1)
print("\nPausing 'X' for 5 seconds.")
t1.pause(True)
time.sleep(5)
print("\nUnpausing 'X' for 5 seconds.")
t1.unpause()
time.sleep(5)
t1.kill()
t2.kill()
t1.join()
t2.join()
print("Done")
# ** EXAMPLE 3) Demonstrate a task that self-terminates after 5 seconds. **
print("\nEX 3) Demonstrate a task that self-terminates after 5 seconds.")
t1 = Threadify(task_run_5s, {"start_time": time.time()}, daemon=False, start=True)
# Join instructs main program to wait on t1 to complete before continuing
t1.join()
print("Done")
# ** EXAMPLE 4) Demonstrate communication with a task via a queue passed in through storage. **
print("\nEX 4) Demonstrate communication with a task via a queue passed in through storage.")
# Create a thread-safe queue for message passing
q = queue.Queue()
# This instance REQUIRES deep_copy=FALSE since Queue is not pickleable.
t1 = Threadify(task_checkqueue, {"queue": q}, deep_copy=False, start=True)
# Wait 3 seconds - then send some messages with varying delays interspersed
time.sleep(3)
q.put("HE")
q.put("LLO")
q.put(" WORLD")
time.sleep(2)
q.put("1")
time.sleep(1)
q.put("2")
time.sleep(2)
q.put("3")
time.sleep(3)
# Send the QUIT message to have task kill itself and then wait for it to die
q.put("QUIT")
t1.join()
print("Done.")
# ** EXAMPLE 5) Fire and forget. Launch a function in a separate thread and have it run to completion. **
print("\nEX 5) Fire and forget. Launch a function in a separate thread and have it run to completion.")
t1 = Threadify(task_dosomething, start=True)
# Join instructs main program to wait on t1 to complete before continuing
t1.join()
print("Done")
# Additional examples to be explored
"""
# ## EXAMPLE) Example of a periodic task accessing and modifying persistent storage ##
print("\nExample of a periodic task accessing and modifying persistent storage.")
t1 = Threadify(task_storage, storage={"a": 10, "b": "A"}, start=True)
time.sleep(10)
t1.kill(wait_until_dead=True)
print("Done")
# ## Exceptions thrown from task body and not ignored ##
t1 = Threadify(exception_task, {"start_time": time.time()}, ignore_task_exceptions=False)
t1.daemon = False
t1.start()
print("\nTask raises exceptions after 5 seconds and doesn't dispose.")
time.sleep(8)
t1.kill()
t1.join()
print("Done")
# ## Exceptions thrown from task body and ignored ##
t1 = Threadify(exception_task, {"start_time": time.time()}, ignore_task_exceptions=True)
t1.daemon = False
t1.start()
print("\nTask raises exceptions after 5 seconds; disposes of them an continues for 3 more seconds.")
time.sleep(8)
t1.kill()
t1.join()
print("Done")
# ## kill a paused thread ##
t1 = Threadify(task_dots, {"a": 123, "b": "M"}, daemon=False)
t1.start()
print("\nStarting a thread that will be paused and then killed.")
time.sleep(5)
t1.pause(True)
print("\nPaused for 5 seconds.")
time.sleep(5)
print("kill paused thread.")
t1.kill()
t1.join()
print("Done")
"""