Skip to content

Instantly share code, notes, and snippets.

@jacobbridges
Created February 22, 2017 16:51
Show Gist options
  • Save jacobbridges/ceece4e5777d75b5afeb9e94786e0fa6 to your computer and use it in GitHub Desktop.
Save jacobbridges/ceece4e5777d75b5afeb9e94786e0fa6 to your computer and use it in GitHub Desktop.
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')
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