|
| 1 | +import time |
| 2 | +import urllib2 |
| 3 | +import threading |
| 4 | +import random |
| 5 | + |
| 6 | +class Producer(threading.Thread): |
| 7 | + """ |
| 8 | + Produces random integers to a list |
| 9 | + """ |
| 10 | + |
| 11 | + def __init__(self, integers, condition): |
| 12 | + """ |
| 13 | + Constructor. |
| 14 | +
|
| 15 | + @param integers list of integers |
| 16 | + @param condition condition synchronization object |
| 17 | + """ |
| 18 | + threading.Thread.__init__(self) |
| 19 | + self.integers = integers |
| 20 | + self.condition = condition |
| 21 | + |
| 22 | + def run(self): |
| 23 | + """ |
| 24 | + Thread run method. Append random integers to the integers list at random time. |
| 25 | + """ |
| 26 | + for i in range(10): |
| 27 | + integer = random.randint(0, 256) |
| 28 | + self.condition.acquire() |
| 29 | + print 'condition acquired by %s' % self.name |
| 30 | + self.integers.append(integer) |
| 31 | + print '%d appended to list by %s' % (integer, self.name) |
| 32 | + print 'condition notified by %s' % self.name |
| 33 | + self.condition.notify() |
| 34 | + print 'condition released by %s' % self.name |
| 35 | + self.condition.release() |
| 36 | + time.sleep(1) |
| 37 | + |
| 38 | +class Consumer(threading.Thread): |
| 39 | + """ |
| 40 | + Consumes random integers from a list |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, integers, condition): |
| 44 | + """ |
| 45 | + Constructor. |
| 46 | +
|
| 47 | + @param integers list of integers |
| 48 | + @param condition condition synchronization object |
| 49 | + """ |
| 50 | + threading.Thread.__init__(self) |
| 51 | + self.integers = integers |
| 52 | + self.condition = condition |
| 53 | + |
| 54 | + def run(self): |
| 55 | + """ |
| 56 | + Thread run method. Consumes integers from list |
| 57 | + """ |
| 58 | + while True: |
| 59 | + self.condition.acquire() |
| 60 | + print 'condition acquired by %s' % self.name |
| 61 | + while True: |
| 62 | + if self.integers: |
| 63 | + integer = self.integers.pop() |
| 64 | + print '%d popped from list by %s' % (integer, self.name) |
| 65 | + break |
| 66 | + print 'condition wait by %s' % self.name |
| 67 | + self.condition.wait() |
| 68 | + print 'condition released by %s' % self.name |
| 69 | + self.condition.release() |
| 70 | + |
| 71 | +def main(): |
| 72 | + integers = [] |
| 73 | + condition = threading.Condition() |
| 74 | + t1 = Producer(integers, condition) |
| 75 | + t2 = Consumer(integers, condition) |
| 76 | + t1.start() |
| 77 | + t2.start() |
| 78 | + t1.join() |
| 79 | + t2.join() |
| 80 | + |
| 81 | +if __name__ == '__main__': |
| 82 | + main() |
| 83 | + |
0 commit comments