multithreading - python timer thread shutdown -
i trying create timer working thread, can exit @ time. python has build in timer, callback function called once?! have no idea why called timer.
then have put sleep in working thread, bad idea. timerthread.cancel() cannot shutdown working thread. if use event exit working thread, working thread can exit after wake up.
i expecting timer working thread, can exit @ time. , don't want working thread blocked.
are there ways realize it?
def show(): while 1: time.sleep(10) print("nice!") if __name__ == '__main__': timerthread = threading.timer(1,show) timerthread.start() while 1: input = str(sys.stdin.readline()) if input == 'exit\n': timerthread.cancel() break;
to point, timer object [1] in python runs once , after period of time executes function. function, though, can start new timer object. example of implementation below.
timerthread = none def timesup(): global timerthread print('nice!') timerthread = timer(10, timesup) timerthread.start() def main(): global timerthread timerthread = timer(10, timesup) timerthread.start() while 1: input = str(sys.stdin.readline()) if input == 'exit\n': timerthread.cancel() break;
overall, due gil [2] issues in python, you'll have issues threading properly, 1 thread has access interpreter @ time. why lot of frameworks in python single threaded, asynchronous frameworks (e.g. gevent [3], tornado [4]). instead of using threads listen on ioloop (eventlets, epoll) , cooperatively yield operation flow other waiting coroutines.
[1] - https://docs.python.org/2/library/threading.html#timer-objects
[2] - https://wiki.python.org/moin/globalinterpreterlock
[3] - http://www.gevent.org/
Comments
Post a Comment