Created
May 20, 2014 11:00
-
-
Save nonZero/ca4ccd0d211937434a67 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import itertools | |
from time import sleep | |
from random import random | |
def main(): | |
c = Container(value=0) | |
adders = [threading.Thread(target=lambda x: x.add(1), args=(c,)) | |
for _ in xrange(10000)] | |
subers = [threading.Thread(target=lambda x: x.add(-1), args=(c,)) | |
for _ in xrange(10000)] | |
printers = [threading.Thread(target=printer, args=(c,)) | |
for _ in xrange(5)] | |
for thread in itertools.chain(printers, adders, subers): | |
thread.start() | |
for thread in itertools.chain(adders, subers): | |
thread.join() | |
print('!!! {} !!!'.format(c.get())) | |
def printer(x): | |
sleep(random()) | |
print(x.get()) | |
class Container(object): | |
def __init__(self, value=None): | |
self.value = value | |
self.lock = threading.Lock() | |
def get(self): | |
return self.value | |
def set(self, value): | |
self.value = value | |
def add(self, value): | |
with self.lock: | |
self.value += value | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment