Skip to content

Instantly share code, notes, and snippets.

@isaaguilar
Created June 17, 2018 04:52
Show Gist options
  • Select an option

  • Save isaaguilar/ed79063fbc666748c5eb5e4655616615 to your computer and use it in GitHub Desktop.

Select an option

Save isaaguilar/ed79063fbc666748c5eb5e4655616615 to your computer and use it in GitHub Desktop.
exit a thread via checking cached values
import time
import threading
import dill as pickle
import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
behaviors={"tcp_nodelay": True, "ketama": True})
lock = threading.Lock()
mc["cached_shutdown_flag"] = False
def reverse(cls):
print "sudo: {1}\nname: {0}".format(cls.name, cls.sudo)
print cls.age()
class Person(threading.Thread):
def __init__(self, name, sudo):
super(Person, self).__init__()
self.shutdown_flag = threading.Event()
self.name = name
self.sudo = sudo
def run(self):
i = 0
while not self.shutdown_flag.is_set() and not mc["cached_shutdown_flag"]:
print ".",
time.sleep(1)
i += 1
if i > 7:
break
# Clean up shop
print i, "CLOSED", not self.shutdown_flag.is_set(), not mc["cached_shutdown_flag"]
def stopper(self):
print "THIS IS SCHEUDULED FOR STOP, {0}".format(self.name)
# can't access the running thread, the following won't work instead use a common resouce
self.shutdown_flag.set()
time.sleep(1)
# Instead, try changing a common flag outside the thread
print "Now trying the cached flag"
mc["cached_shutdown_flag"] = True
def age(self):
return 42
def printInfo(self):
print "name: {0}\nsudo: {1}".format(self.name, self.sudo)
printReverse = reverse
if __name__ == "__main__":
# person = Person("isa aguilar", "isa")
# person.printInfo()
# person.printReverse()
t = Person("Isa Aguilar", "isa")
t.start()
with open('person.pkl', 'wb') as output:
pickle.dump(t, output, pickle.HIGHEST_PROTOCOL)
del t
time.sleep(2)
with open('person.pkl', 'rb') as input:
# unpickeling grant access to the instance, not the thread
print "attempting to stop"
t = pickle.load(input)
t.stopper()
t.shutdown_flag.set()
# Calling the cached_shutdown_flag anytime will kill the process
# mc["cached_shutdown_flag"] = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment