diff --git a/Demos/Demo23/Unit1.dfm b/Demos/Demo23/Unit1.dfm index b3f8fa35..d4d7b0ad 100644 --- a/Demos/Demo23/Unit1.dfm +++ b/Demos/Demo23/Unit1.dfm @@ -26,7 +26,7 @@ object Form1: TForm1 Font.Name = 'Consolas' Font.Style = [] Lines.Strings = ( - 'import threading' + 'import threading_test' 'import sys' 'try:' ' count = int(sys.argv[1])' @@ -35,7 +35,7 @@ object Form1: TForm1 '' 'for i in range(count):' ' print ("**** Pass", i)' - ' threading._test()' + ' threading_test._test()' 'print ("**** Done.")') ParentFont = False ScrollBars = ssBoth diff --git a/Demos/Demo23/threading_test.py b/Demos/Demo23/threading_test.py new file mode 100644 index 00000000..cf76f22e --- /dev/null +++ b/Demos/Demo23/threading_test.py @@ -0,0 +1,96 @@ +from threading import * +from collections import deque +from time import sleep + +def _test(): + + class BoundedQueue(): + + def __init__(self, limit): + self.mon = RLock() + self.rc = Condition(self.mon) + self.wc = Condition(self.mon) + self.limit = limit + self.queue = deque() + + def put(self, item): + self.mon.acquire() + while len(self.queue) >= self.limit: + self._note("put(%s): queue full", item) + self.wc.wait() + self.queue.append(item) + self._note("put(%s): appended, length now %d", + item, len(self.queue)) + self.rc.notify() + self.mon.release() + + def get(self): + self.mon.acquire() + while not self.queue: + self._note("get(): queue empty") + self.rc.wait() + item = self.queue.popleft() + self._note("get(): got %s, %d left", item, len(self.queue)) + self.wc.notify() + self.mon.release() + return item + + def _note(self, format, *args): + format = format % args + ident = get_ident() + try: + name = current_thread().name + except KeyError: + name = "" % ident + format = "%s: %s" % (name, format) + print(format) + + class ProducerThread(Thread): + + def __init__(self, queue, quota): + Thread.__init__(self, name="Producer") + self.queue = queue + self.quota = quota + + def run(self): + from random import random + counter = 0 + while counter < self.quota: + counter = counter + 1 + self.queue.put("%s.%d" % (self.name, counter)) + sleep(random() * 0.00001) + + + class ConsumerThread(Thread): + + def __init__(self, queue, count): + Thread.__init__(self, name="Consumer") + self.queue = queue + self.count = count + + def run(self): + while self.count > 0: + item = self.queue.get() + print(item) + self.count = self.count - 1 + + NP = 3 + QL = 4 + NI = 5 + + Q = BoundedQueue(QL) + P = [] + for i in range(NP): + t = ProducerThread(Q, NI) + t.name = ("Producer-%d" % (i+1)) + P.append(t) + C = ConsumerThread(Q, NI*NP) + for t in P: + t.start() + sleep(0.000001) + C.start() + for t in P: + t.join() + C.join() + +_test() \ No newline at end of file