summaryrefslogtreecommitdiff
path: root/threads/prod_cons.py
diff options
context:
space:
mode:
authorchzhang <zch921005@126.com>2022-12-03 17:04:42 +0800
committerchzhang <zch921005@126.com>2022-12-03 17:04:42 +0800
commit89382791ea9896172bdf8f15e8b30e944664fa15 (patch)
tree33e9d856bda3e6046f967ed649ed9e8382b669b9 /threads/prod_cons.py
parent8f4e69ad9557555c1869662114aa9b1909889d6e (diff)
producer & consumer
Diffstat (limited to 'threads/prod_cons.py')
-rw-r--r--threads/prod_cons.py54
1 files changed, 54 insertions, 0 deletions
diff --git a/threads/prod_cons.py b/threads/prod_cons.py
new file mode 100644
index 0000000..c781d92
--- /dev/null
+++ b/threads/prod_cons.py
@@ -0,0 +1,54 @@
+
+
+from threading import Thread
+from queue import Queue
+import random
+import time
+
+
+BUF_SIZE = 10
+
+q = Queue(BUF_SIZE)
+
+
+class ProducerThread(Thread):
+ def __init__(self, name=None):
+ super(ProducerThread, self).__init__()
+ self.name = name
+
+ def run(self):
+ while True:
+ if not q.full():
+ item = random.randint(1, 10)
+ q.put(item)
+ print(f'{self.name}({self.ident}): puts {item}, current queue size is {q.qsize()}')
+ time.sleep(random.random())
+ else:
+ print(f'{self.name}({self.ident}): is full, cannot produce.')
+ time.sleep(random.random()*2)
+
+
+class ConsumerThread(Thread):
+ def __init__(self, name=None):
+ super(ConsumerThread, self).__init__()
+ self.name = name
+
+ def run(self):
+ while True:
+ if not q.empty():
+ item = q.get()
+ print(f'{self.name}({self.ident}): gets {item}, current queue size is {q.qsize()}')
+ time.sleep(random.random())
+ else:
+ print(f'{self.name}({self.ident}): is empty, cannot consume, waiting.')
+ time.sleep(random.random()*2)
+
+
+if __name__ == '__main__':
+ p1 = ProducerThread(name='producer-1')
+ p1.start()
+ time.sleep(2)
+
+ c1 = ConsumerThread(name='consumer-1')
+ c1.start()
+