Created
February 22, 2017 16:51
-
-
Save jacobbridges/ceece4e5777d75b5afeb9e94786e0fa6 to your computer and use it in GitHub Desktop.
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
from theading import Thread | |
class StoppableThread(Thread): | |
"""A thread which can be stopped from thread reference.""" | |
do_run = True | |
def stop(self): | |
"""Stop this thread.""" | |
self.do_run = False | |
def run(self): | |
"""What the thread does (the worker code).""" | |
try: | |
while self.do_run: | |
if self._target: | |
self._target(*self._args, **self._kwargs) | |
finally: | |
# Avoid a refcycle if the thread is running a function with | |
# an argument that has a member that points to the thread. | |
del self._target, self._args, self._kwargs | |
print('Thread is stopping') |
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
from stoppable_thread import StoppableThread as ST | |
from time import sleep | |
# Create a worker function | |
def worker(): | |
print("I'M STILL ALIVE!!") | |
sleep(3) | |
t = ST(target=worker) | |
sleep(10) | |
# I'M STILL ALIVE!! | |
# I'M STILL ALIVE!! | |
# I'M STILL ALIVE!! | |
t.stop() | |
# Thread is stopping |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment