Skip to content

Instantly share code, notes, and snippets.

@grasses
Created October 2, 2015 06:45
Show Gist options
  • Save grasses/efd81dfb792d0be08b49 to your computer and use it in GitHub Desktop.
Save grasses/efd81dfb792d0be08b49 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Queue import Queue
import threading, random, time
__author__ = 'homeway'
__version__ = '2015.10.01'
class producer(threading.Thread):
def __init__(self, queue, **config):
threading.Thread.__init__(self)
self.queue = queue
self.limit = config["limit"]
def run(self):
count = 0
while True:
if self.queue.qsize() < self.limit:
count = count + 1
self.queue.put(random.randrange(1, 9999999))
time.sleep(0.5)
if count > 10:
print("Producer want to break loop")
self.queue.put("break")
break
class consumer(threading.Thread):
def __init__(self, queue, **config):
threading.Thread.__init__(self)
self.queue = queue
self.limit = config["limit"]
def run(self):
while True:
if self.queue.qsize() > 0:
msg = self.queue.get()
if msg == "break":
print("Comsumer got break now, break")
break
print("Consumer got ->", msg)
else:
print("Queue is empty, consumer wait...")
time.sleep(1)
if __name__ == "__main__":
qu = Queue()
config = {"limit": 100}
produce = producer(qu, **config)
consume = consumer(qu, **config)
print("Now program is runing...")
produce.start()
consume.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment