1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import threading import time con = threading.Condition() class Producer(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): global x with con: while x >= self.num: con.wait() for i in range(x, self.num+1): if(i!=self.num): print(i, end=" ") else: print(i) x += 1 time.sleep(0.1) con.notify() class Consumer(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): global x with con: while x <= 0: con.wait() for i in range(self.num,-1, -1): if(i!=-1): print(i, end=" ") else: print(i) x -= 1 time.sleep(0.1) con.notify_all() num = input() x = 0 num = int(num) p = Producer(num) c = Consumer(num) p.start() c.start() p.join() c.join()
|