-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pitfall16 future
218 lines (174 loc) · 7.23 KB
/
Pitfall16 future
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
conlcusion: watch out for the format !!!!!
**********************
import concurrent.futures
import time
def api_call():
time.sleep(2) # Simulating a long-running API call
return "API call completed successfully"
def main():
t0=time.time()
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(api_call)
result = future.result(timeout=5)
print("Got result:", result)
except concurrent.futures.TimeoutError:
print('entering time out:',time.time()-t0)
print("TimeoutError: Future result not available within 1 second")
if __name__ == "__main__":
main()
Got result: API call completed successfully
**********************
import concurrent.futures
import time
def api_call():
time.sleep(5) # Simulating a long-running API call
return "API call completed successfully"
def main():
t0=time.time()
try:
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(api_call)
result = future.result(timeout=1)
print("Got result:", result)
except concurrent.futures.TimeoutError:
print('entering time out:',time.time()-t0)
print("TimeoutError: Future result not available within 1 second")
if __name__ == "__main__":
main()
entering time out: 5.002657890319824
TimeoutError: Future result not available within 1 second
**********************
import concurrent.futures
import time
def api_call():
time.sleep(2) # Simulating a long-running API call
return "API call completed successfully"
def main():
t0=time.time()
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(api_call)
try:
print("Waiting for result with a timeout of 1 second")
result = future.result(timeout=1)
print("Got result:", result)
except concurrent.futures.TimeoutError:
print('entering time out:',time.time()-t0)
print("TimeoutError: Future result not available within 1 second")
if __name__ == "__main__":
main()
Waiting for result with a timeout of 1 second
entering time out: 0.10640907287597656
TimeoutError: Future result not available within 1 second
***********************************************************************************************
# if you handle exception in your function, futures.FIRST_EXCEPTION will not work. The real result is that it will wait for both threads to complete == ALL_COMPLETED
import concurrent.futures
import time
def api_call():
time.sleep(2) # Simulating a long-running API call
return "API call completed successfully"
def function_with_exception():
try:
raise ValueError("This is a sample exception")
except:
return 'raised exception'
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future1 = executor.submit(function_with_exception)
future2 = executor.submit(api_call)
print('***** function_with_exception:', future1.done())
print('***** api_call:', future2.done())
tt1 = time.time()
completed_futures, _ = concurrent.futures.wait([future1, future2], return_when=concurrent.futures.FIRST_EXCEPTION)
tt2 = time.time()
print(f"Time spent in wait: {tt2 - tt1} seconds")
print('***** completed_futures:', completed_futures)
for completed_future in completed_futures:
try:
result = completed_future.result()
print("Result:", result)
except Exception as e:
print(f"Exception occurred: {e}")
print('***** function_with_exception:', future1.done())
print('***** api_call:', future2.done())
if __name__ == "__main__":
main()
***********************************************************************************************
# if you not handle exception, then FIRST_EXCEPTION will work
import concurrent.futures
import time
def api_call():
time.sleep(2) # Simulating a long-running API call
return "API call completed successfully"
def function_with_exception():
# try:
raise ValueError("This is a sample exception")
# except:
# return 'raised exception'
def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
future1 = executor.submit(function_with_exception)
future2 = executor.submit(api_call)
print('***** function_with_exception:', future1.done())
print('***** api_call:', future2.done())
tt1 = time.time()
completed_futures, _ = concurrent.futures.wait([future1, future2], return_when=concurrent.futures.FIRST_EXCEPTION)
tt2 = time.time()
print(f"Time spent in wait: {tt2 - tt1} seconds")
print('***** completed_futures:', completed_futures)
for completed_future in completed_futures:
try:
result = completed_future.result()
print("Result:", result)
except Exception as e:
print(f"Exception occurred: {e}")
print('***** function_with_exception:', future1.done())
print('***** api_call:', future2.done())
if __name__ == "__main__":
main()
***** function_with_exception: True
***** api_call: False
Time spent in wait: 0.00099945068359375 seconds
***** completed_futures: {<Future at 0x1c9a7195970 state=finished raised ValueError>}
Exception occurred: This is a sample exception
***** function_with_exception: True
***** api_call: False
***********************************************************************************************
***********************************************************************************************
problem with with block statement, it will wait for both threads to complete and then start another function.
unless, the with block is in the main thread. if in a separate standalone function, the first complete will not work as expected
import concurrent.futures
import time
from concurrent.futures import ThreadPoolExecutor
def some_long_running_task1():
time.sleep(3)
return "Task 1 completed successfully!"
def some_long_running_task2():
time.sleep(10)
return "Task 2 completed successfully!"
def run_task_in_executor():
executor = ThreadPoolExecutor(max_workers=2)
future_result1 = executor.submit(some_long_running_task1)
future_result2 = executor.submit(some_long_running_task2)
print("Tasks submitted, not waiting for completion.", time.time())
completed_futures, _ = concurrent.futures.wait(
[future_result1, future_result2],
timeout=None,
return_when=concurrent.futures.FIRST_COMPLETED
)
# You can iterate over completed futures without blocking
for future in completed_futures:
# Handle the completed future, if needed
result = future.result()
print("Task completed in wait loop.", result, time.time())
try:
result = future_result2.result(timeout=6)
except Exception as err:
print(err)
print('serve task 1...........')
# This part is reached after exiting the with block
def my_func():
run_task_in_executor()
print('after run_task_in_executor:', time.time())
# Call the function that sets up the ThreadPoolExecutor
my_func()