生产者消费者

今天总算理解这个模型的主要用途了

  • 削峰:削峰简单来说就是处理生产者和消费者速度不匹配的问题
  • 解耦:解耦简单来说就是拆逻辑,以便于维护和扩容
[root@Da scripts]# cat multi_thread_5.py
from threading import Thread, current_thread
from queue import Queue
import time
class Producer(Thread):
    def run(self):
        while True:
            if queue.qsize() < 100:
                job_data = 'job-{}'.format(int(time.time()))
                queue.put(job_data)
                print('[Producer-{}]: Create job [{}] and send to Queue, current queue size {}'.format(current_thread().name, job_data, queue.qsize()))
            time.sleep(0.5)

class Consumer(Thread):
    def run(self):
        while True:
            if queue.qsize() > 0:
                job_data = queue.get()
                print('[Consumer-{}]: Get job data [{}], starting process job...'.format(current_thread().name, job_data))
            time.sleep(0.5)

if __name__ == '__main__':
    queue = Queue()
    for i in range(5):
        p = Producer()
        p.start()
    for i in range(3):
        c = Consumer()
        c.start()

results matching ""

    No results matching ""