The old counter code is demonstrated in baaad where a variable in a function that is executed by more than one thread is incremented by each thread.
I've since switched to the myCounter way of doing things and now the program runs much longer (but still crashes after a while), but I wanted to try to create a problem to better understand the issue, so I experimented with other ways of doing it. Unfortunately, everything works just fine.
Please help me write thread-unsafe code.
EDIT: Friendlier printing. I'm hoping for either an individual thread, or the main thread to crash.
import itertools, threading, time
class myCounter(object):
def __init__(self, startval=0, step=1):
self.counter = itertools.count(startval, step)
self.at = startval
def next(self):
self.at = self.counter.next()
return self.at
def get(self):
return self.at
def reset(self):
self.counter = itertools.count(0)
self.at = 0
class myOtherCounter(object):
def __init__(self, startval=0, step=1):
self.counter = startval
self.step = step
def next(self):
self.counter += self.step
return self.counter
def get(self):
return self.counter
def reset(self):
self.counter = 0
def torture(name, counter):
while counter.next() < 50000:
pass
print "{0}:Done -> {1}".format(name, counter.get())
global x
x = 0
def baaad(name):
global x
while x < 50000:
x += 1
print "{0}:Done -> {1}".format(name, x)
if __name__ == "__main__":
b = myCounter()
c = myOtherCounter()
[threading.Thread(target=torture, args=["myCounterThread{0}".format(i), b]).start() for i in range(1, 4)]
[threading.Thread(target=torture, args=["myOtherCounterThread{0}".format(i), c]).start() for i in range(1, 4)]
[threading.Thread(target=baaad, args=["myBADCounterThread{0}".format(i)]).start() for i in range(1, 4)]
This post has been edited by Python_4_President: 26 November 2012 - 12:53 PM

New Topic/Question
Reply



MultiQuote




|