python 生产者消费者不同的方法实现(线程进程TCP)

https://blog.csdn.net/u014595589/article/details/53288168

# coding: utf-8
import threading
import time
import Queue


class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue

    def run(self):
        while True:
            msg = self._queue.get()

            if isinstance(msg, str) and msg == 'quit':
                break

            time.sleep(1)
            print 'consumer receive msg: %s' % msg

        print 'consumer finished'


def build_consumer_pool(size, queue):
    consumers = []

    for i in range(size):
        c = Consumer(queue=queue)
        c.start()
        consumers.append(c)

    return consumers


def Producer():
    q = Queue.Queue()
    consumers = build_consumer_pool(3, q)

    i = 0
    while i < 12:
        print 'producer put msg: %s' % i
        q.put(str(i))

        i += 1

    for c in consumers:
        q.put('quit')

    for c in consumers:
        c.join()


if __name__ == '__main__':
    Producer()

进程管理

# coding: utf-8
from multiprocessing.dummy import Pool as ThreadPool
import time


def consumer(msg):
    print 'consumer receive msg: %s' % msg
    time.sleep(1)
    return msg


def producer():
    items = []
    pool = ThreadPool(4)

    i = 0
    while i < 12:
        print 'producer put msg: %s' % i
        items.append(str(i))
        i += 1

    results = pool.map(consumer, items)
    pool.close()
    pool.join()
    print results


if __name__ == '__main__':
    producer()

猜你喜欢

转载自blog.csdn.net/u012611644/article/details/80530165
今日推荐