David Blume's GitList
Repositories
testpython.git
Code
Commits
Branches
Tags
Search
Tree:
0d6d4d4
Branches
Tags
main
python2
testpython.git
counter
counter.py
Compatibility with Python 2.
David Blume
commited
0d6d4d4
at 2016-08-14 11:18:22
counter.py
Blame
History
Raw
#!/usr/bin/env python # From https://dl.dropboxusercontent.com/u/3967849/pyru/_build/html/threading.html from __future__ import print_function import threading, Queue ############################################################################# _counter = 0 counter_queue = Queue.Queue() def counter_manager(): 'I have EXCLUSIVE rights to update the _counter variable' global _counter while True: increment = counter_queue.get() _counter += increment print_queue.put([ 'The count is %d' % _counter, '---------------']) counter_queue.task_done() ############################################################################# print_queue = Queue.Queue() def print_manager(): 'I have EXCLUSIVE rights to call the "print" keyword' while True: job = print_queue.get() for line in job: print(line) print_queue.task_done() ############################################################################# def worker(): 'My job is to increment the counter and print the current count' counter_queue.put(1) def run(): # Set up the counter manager t = threading.Thread(target=counter_manager) t.daemon = True t.start() del t # Set up the print manager t = threading.Thread(target=print_manager) t.daemon = True t.start() del t # Start doing work print_queue.put(['Starting up']) worker_threads = [] for i in range(10): t = threading.Thread(target=worker) worker_threads.append(t) t.start() for t in worker_threads: t.join() counter_queue.join() print_queue.put(['Finishing up']) print_queue.join() if __name__ == '__main__': run()