生产者和消费者 - Python中的多个线程

时间:2015-10-10 15:04:26

标签: python multithreading semaphore producer-consumer

所以我已经为生产者和消费者提供了这个代码;

import threading

import time

import random

N = 8


buffer = N * [None]

free = threading.Semaphore(N)

items = threading.Semaphore(0)

def prod():

    n = 0
    i = 0
    while True:
        time.sleep(random.random())
        free.acquire()
        buffer[i] = n
        i = (i + 1) % N
        n += 1
        items.release()

def cons():

    i = 0
    while True:
        time.sleep(random.random())
        items.acquire()
        print(buffer[i])
        i = (i + 1) % N
        free.release()

def main():

    p = threading.Thread(target=prod, args=[])
    c = threading.Thread(target=cons, args=[])
    p.start()
    c.start()
    p.join()
    c.join()

main()

但我希望能够为生产者和消费者分别拥有三个主题。有人可以建议我使用第三个信号量来做到这一点吗?谢谢。

1 个答案:

答案 0 :(得分:1)

假设这不是关于信号量的功课,而你想要一个真正的解决方案,你应该使用Queue对象,它可以自己处理所有这些。如果我理解正确,你想要三个生产者和三个消费者共享一个缓冲区,最多可以有8个项目。如果是这种情况,代码可以简化为:

import threading
import Queue

def prod(queue):
    n = 0
    while True:
        time.sleep(random.random())
        queue.put(n)
        n += 1

def cons(queue):
    while True:
        time.sleep(random.random())
        n = queue.get()
        print n

def main():
    N = 8
    queue = Queue.Queue(N)
    threads = []
    for i in range(3):
        threads.append(threading.Thread(target=cons, args=[queue])))
        threads.append(threading.Thread(target=prod, args=[queue])))
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join() # this will never really finish, because the threads run forever

如果您对如何在内部实施队列感兴趣,可以看到源代码here