2015-10-10 82 views
3

所以我有生產者和消費者的代碼;生產者和消費者 - Python中的多個線程

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

假設這不是關於信號量的功課,並且您想要一個真正的解決方案,您應該使用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

+0

感謝您的幫助,但它是一個任務,我必須寫它與第三互斥信號量。你能告訴我這樣寫嗎? – JoC5