Commit 3ca730c8 authored by Jeremy Hylton's avatar Jeremy Hylton

Modify tests so they run more quickly.

Modify tests so that thread execution is actually interleaved; the old
version ended up having one thread run to completion, then the next, etc.

Use explicit counter to keep track of child threads, rather than
counting on long sleep to be long enough.
parent 128358b9
from Sync import Synchronized from Sync import Synchronized
import thread import thread
from random import random from random import random
from time import sleep from time import sleep
class P(Synchronized): class P(Synchronized):
def __init__(self,*args,**kw): def __init__(self,*args,**kw):
self.count=0 self.count=0
def inc(self): def inc(self):
c=self.count c = self.count
sleep(random()) if random() > 0.7:
self.count=self.count+1 sleep(1)
return c,self.count self.count = self.count + 1
return c, self.count
def incn(self,n): def incn(self,n):
c=self.count c = self.count
for i in range(n): self.inc() for i in range(n):
return c,self.count self.inc()
return c, self.count
p=P(1,2,spam=3) p = P(1, 2, spam=3)
def test(): def test():
for i in range(8):
for i in range(10): n = 3
n=3 old, new = p.incn(n)
old,new=p.incn(n) if old + n != new:
print old,new print 'oops'
if old+n != new: print 'oops' sleep(2)
thread_finished()
for i in range(10): thread.start_new_thread(test,()) def thread_finished(lock=thread.allocate_lock()):
sleep(50) global num_threads
lock.acquire()
num_threads = num_threads - 1
lock.release()
num_threads = 8
for i in range(num_threads):
thread.start_new_thread(test, ())
while num_threads > 0:
sleep(1)
import ThreadLock, thread import ThreadLock, thread
from random import random from random import random
from time import sleep from time import sleep
...@@ -30,7 +29,8 @@ class P(Base): ...@@ -30,7 +29,8 @@ class P(Base):
def inc(self): def inc(self):
c=self.count c=self.count
sleep(random()) if random() > 0.7:
sleep(1)
self.count=self.count+1 self.count=self.count+1
return c,self.count return c,self.count
...@@ -43,12 +43,24 @@ p=P(1,2,spam=3) ...@@ -43,12 +43,24 @@ p=P(1,2,spam=3)
def test(): def test():
for i in range(10): for i in range(8):
n=3 n = 3
old,new=p.incn(n) old, new = p.incn(n)
print old,new if old + n != new:
if old+n != new: print 'oops' print 'oops'
sleep(3)
thread_finished()
def thread_finished(lock=thread.allocate_lock()):
global num_threads
lock.acquire()
num_threads = num_threads - 1
lock.release()
num_threads = 8
for i in range(num_threads):
thread.start_new_thread(test, ())
for i in range(10): thread.start_new_thread(test,()) while num_threads > 0:
sleep(50) sleep(1)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment