Skip to content

Instantly share code, notes, and snippets.

@cyberbikepunk
Last active September 13, 2015 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberbikepunk/be321691503eade98e02 to your computer and use it in GitHub Desktop.
Save cyberbikepunk/be321691503eade98e02 to your computer and use it in GitHub Desktop.
a simple threaded counter implemented in pythobn
from logging import basicConfig, DEBUG, debug
from threading import Lock, Thread, current_thread, enumerate
from time import sleep
from random import random
basicConfig(level=DEBUG, format='[%(thread)d: %(message)s]')
class Counter(object):
def __init__(self, start=0):
self.lock = Lock()
self.value = start
def increment(self):
debug('Waiting for lock')
self.lock.acquire()
try:
debug('Acquired lock')
self.value += 1
finally:
self.lock.release()
def worker(c, _):
for i in range(2):
pause = random()
debug('Sleeping %0.02f', pause)
sleep(pause)
c.increment()
debug('Done')
counter = Counter()
for i in range(2):
t = Thread(target=worker, args=(counter, i))
t.start()
debug('Waiting for worker threads')
main_thread = current_thread()
for t in enumerate():
if t is not main_thread:
t.join()
debug('Counter: %d', counter.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment