Created
July 31, 2019 12:36
-
-
Save Hiroshiba/5cce521fa42be2b7b3f7532fec01bdd7 to your computer and use it in GitHub Desktop.
`timeout-decorator` with `threading` or `multiprocessing`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
import threading | |
import time | |
import timeout_decorator | |
def countup(): | |
for i in range(1, 10): | |
time.sleep(1) | |
print(' {} seconds have passed '.format(i)) | |
@timeout_decorator.timeout(2.5, use_signals=True) | |
def countup_use_signals(): | |
countup() | |
@timeout_decorator.timeout(2.5, use_signals=False) | |
def countup_unuse_signals(): | |
countup() | |
def main(): | |
try: | |
print(' Start use_signals=True ') | |
countup_use_signals() | |
except Exception as e: | |
print(f' error: {e}') | |
try: | |
print(' Start use_signals=False ') | |
countup_unuse_signals() | |
except Exception as e: | |
print(f' error: {e}') | |
if __name__ == '__main__': | |
print('main thread') | |
main() | |
print('multiprocessing') | |
p = multiprocessing.Process(target=main) | |
p.start() | |
p.join() | |
print('threading') | |
t = threading.Thread(target=main) | |
t.start() | |
t.join() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
main thread | |
Start use_signals=True | |
1 seconds have passed | |
2 seconds have passed | |
error: 'Timed Out' | |
Start use_signals=False | |
1 seconds have passed | |
2 seconds have passed | |
error: 'Timed Out' | |
multiprocessing | |
Start use_signals=True | |
1 seconds have passed | |
2 seconds have passed | |
error: 'Timed Out' | |
Start use_signals=False | |
1 seconds have passed | |
2 seconds have passed | |
error: 'Timed Out' | |
threading | |
Start use_signals=True | |
error: signal only works in main thread | |
Start use_signals=False | |
1 seconds have passed | |
2 seconds have passed | |
error: 'Timed Out' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment