# fair.py from __future__ import print_function from threading import Thread from collections import deque import time import math SLOW_N = 100000 FAST_N = 1000000 # fair.py from threading import Thread from collections import deque import time SLOW_N = 100000 FAST_N = 1000000 stop = False do_stop = False def slow(n, s=""): global stop items = [] start = time.time() while n > 0 and not stop: items.insert(0,n) n -= 1 if do_stop: stop = True end = time.time() print("slow%s: %f (%d left)\n" % (s, end-start, n), end="") def fast(n, s=""): global stop items = deque() start = time.time() while n > 0 and not stop: items.appendleft(n) n -= 1 if do_stop: stop = True end = time.time() print("fast%s: %f (%d left)\n" % (s, end-start, n), end="") print("Sequential execution") slow(SLOW_N) fast(FAST_N) print("Threaded execution") t1 = Thread(target=slow,args=(SLOW_N,)) t2 = Thread(target=fast,args=(FAST_N,)) t1.start(); t2.start() t1.join(); t2.join(); print("Treaded, balanced execution:") do_stop = False stop = False t1 = Thread(target=fast,args=(FAST_N, " A")) t2 = Thread(target=fast,args=(FAST_N, " B")) t3 = Thread(target=fast,args=(FAST_N, " C")) t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); print("Treaded, balanced execution, with quickstop:") do_stop = True stop = False t1 = Thread(target=fast,args=(FAST_N, " A")) t2 = Thread(target=fast,args=(FAST_N, " B")) t3 = Thread(target=fast,args=(FAST_N, " C")) t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join();