Last active
September 13, 2015 09:04
-
-
Save cyberbikepunk/be321691503eade98e02 to your computer and use it in GitHub Desktop.
a simple threaded counter implemented in pythobn
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
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