Answer the question
In order to leave comments, you need to log in
How to set a limit on the execution time of a piece of code?
In my code, it can happen that the line will be executed for an unforgivably long time.
It is necessary to organize the principle according to which if it is processed longer, for example 1 second, then its execution will be terminated.
I wanted to solve it using multithreading, but since I don’t rummage, I didn’t succeed.
After I used the chips of Unix systems, namely signal, but in-1 the error occurs elsewhere, and in-2 this solution cannot be used on Windows.
Please show a code example that describes the above principle using threads using multiprocessing or threading, I will be very grateful
Answer the question
In order to leave comments, you need to log in
Be sure to set daemon=True for the thread, otherwise the program will wait for it to complete
import time
import threading
import random
def longworker():
t = random.randint(10,20)
time.sleep(t)
print('воркер работал {} секунд'.format(t))
w = threading.Thread(target=longworker, daemon=True)
w.start()
w.join(timeout=15)
if w.isAlive():
print('Завершаем работу не дождавшись воркера')
exit()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question