生产者和消费者-Python中的多线程
所以我为生产者和消费者准备了这个代码生产者和消费者-Python中的多线程,python,multithreading,semaphore,producer-consumer,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())
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()
但是我希望能够为生产者和消费者分别提供三个线程。有人能建议我用第三个信号灯来做这件事吗?谢谢 假设这不是一个关于信号量的家庭作业,并且您想要一个真正的解决方案,那么您应该使用对象,它可以自己处理所有这些。如果我理解正确,您需要三个生产者和三个消费者共享一个缓冲区,最多可以有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
如果您对队列如何在内部实现感兴趣,可以查看源代码。谢谢您的帮助,但这是一个赋值,我必须使用第三个互斥信号量来编写它。请你也给我看看那样写的好吗?