Skip to content

Instantly share code, notes, and snippets.

@centaurialpha
Last active October 4, 2018 21:23
Show Gist options
  • Save centaurialpha/4deea073f23a58bb308ab59d74694225 to your computer and use it in GitHub Desktop.
Save centaurialpha/4deea073f23a58bb308ab59d74694225 to your computer and use it in GitHub Desktop.
import time
import random
import signal
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
TIMEOUT = 3
def timeout_signal_handler(signum, frame):
raise TimeoutError()
def main():
signal.signal(signal.SIGALRM, timeout_signal_handler)
signal.signal(signal.SIGINT, timeout_signal_handler)
signal.alarm(TIMEOUT)
futures = []
try:
with ProcessPoolExecutor(max_workers=2) as executor:
for i in range(10):
futures.append(executor.submit(do, i))
except TimeoutError as reason:
print("Canceling tasks...")
for e, f in enumerate(futures):
f.cancel()
print(" Task [{}] {}".format(e, f))
signal.alarm(0)
def do(task_name):
ttime = random.randint(1, 5)
print("Running task [{}] - Time: {}...".format(task_name, ttime))
time.sleep(ttime)
print("Finished task [{}]".format(task_name))
if __name__ == "__main__":
main()
@centaurialpha
Copy link
Author

ThreadPoolExecutor:

Running task [0] - Time: 1...
Running task [1] - Time: 5...
Finished task [0]
Running task [2] - Time: 3...
Canceling tasks...
     Task [0] <Future at 0x7fa6eca02d30 state=finished returned NoneType>
     Task [1] <Future at 0x7fa6ec9bdd30 state=running>
     Task [2] <Future at 0x7fa6ebe33f28 state=running>
     Task [3] <Future at 0x7fa6ebe3b2e8 state=cancelled>
     Task [4] <Future at 0x7fa6ebe3b470 state=cancelled>
     Task [5] <Future at 0x7fa6ebe3b550 state=cancelled>
     Task [6] <Future at 0x7fa6ebe3b630 state=cancelled>
     Task [7] <Future at 0x7fa6ebe3b710 state=cancelled>
     Task [8] <Future at 0x7fa6ebe3b7f0 state=cancelled>
     Task [9] <Future at 0x7fa6ebe3b8d0 state=cancelled>
Finished task [2]
Finished task [1]

ProcessPoolExecutor:

Running task [1] - Time: 4...
Running task [0] - Time: 3...
Canceling tasks...
     Task [0] <Future at 0x7f0c01576e10 state=running>
     Task [1] <Future at 0x7f0c015835c0 state=running>
     Task [2] <Future at 0x7f0c01583668 state=running>
     Task [3] <Future at 0x7f0c01583710 state=running>
     Task [4] <Future at 0x7f0c015837f0 state=running>
     Task [5] <Future at 0x7f0c015838d0 state=cancelled>
     Task [6] <Future at 0x7f0c015839b0 state=cancelled>
     Task [7] <Future at 0x7f0c01583a90 state=cancelled>
     Task [8] <Future at 0x7f0c01583b70 state=cancelled>
     Task [9] <Future at 0x7f0c01583c50 state=cancelled>
Finished task [0]
Running task [2] - Time: 1...
Finished task [1]
Running task [3] - Time: 4...
Finished task [2]
Running task [4] - Time: 4...
Finished task [3]
Finished task [4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment