Created
July 30, 2015 03:41
-
-
Save aaronchall/1ecb40580e549923cdaa 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
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