Skip to content

Instantly share code, notes, and snippets.

@aaronchall
Created July 30, 2015 03:41
Show Gist options
  • Save aaronchall/1ecb40580e549923cdaa to your computer and use it in GitHub Desktop.
Save aaronchall/1ecb40580e549923cdaa to your computer and use it in GitHub Desktop.
import threading
from time import sleep, time
from itertools import count
class WorkThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(WorkThread, self).__init__(target=self.target)
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
class Sleeps(WorkThread):
def target(self): #... sleep and wakeup every second
while not self.stopped():
sleep(1)
class Whiles(WorkThread):
def target(self): #... run until killed
while not self.stopped():
pass
def main_thread(): #... count hard for ten seconds
counter = count()
start = time()
end = start + 10
while end > time():
i = next(counter)
return i
def main(): #... print count after running main with both.
thread1 = Sleeps()
thread1.daemon = True
thread1.start()
sleep_result = main_thread()
thread1.stop()
thread2 = Whiles()
thread2.daemon = True
thread2.start()
while_result = main_thread()
thread2.stop()
print('\nsleep result: ' + str(sleep_result))
print('while result: ' + str(while_result))
efficiency_factor = sleep_result/float(while_result)
print('sleep allowed {0} times work\n'
'done relative to while'.format(efficiency_factor))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment