生产者消费者在python中为每个3个线程

时间:2015-10-16 11:35:11

标签: python multithreading semaphore

我正在尝试做一个制片人消费者计划。我让它工作得很好,每个都有一个线程,我试图修改它以运行每个线程的三个线程。似乎每个消费者线程都试图消耗每个已发布的项目。

# N is the number of slots in the buffer
N = 8
n = 0
i=0
j=0
# initialise buf with the right length, but without values
buf = N * [None]


free = threading.Semaphore(N)
items = threading.Semaphore(0)
block = threading.Semaphore(1)

# a function for the producer thread
def prod(n, j):
    while True:
        time.sleep(random.random())
        free.acquire()
        # produce a number and add it to the buffer
        buf[i] = n
        #print("produced")
        j = (j + 1) % N
        n += 1
        items.release()


# a function for the consumer thread
def cons(th):
    global i
    while True:
        time.sleep(random.random())
        #acquire items to allow the consumer to print. 
        items.acquire()
        print(buf[i])
        print("consumed, th:{} i:{}".format(th, i))
        i = (i + 1) % N
        #time.sleep(3)
        free.release()





# a main function
def main():
    p1 = threading.Thread(target=prod, args=[n,j])
    p2 = threading.Thread(target=prod, args=[n,j])
    p3 = threading.Thread(target=prod, args=[n,j])
    c1 = threading.Thread(target=cons, args=[1])
    c2 = threading.Thread(target=cons, args=[2])
    c3 = threading.Thread(target=cons, args=[3])

    p1.start()
    p2.start()
    p3.start()
    c1.start()
    c2.start()
    c3.start()
    p1.join()
    p2.join()
    p3.join()
    c1.join()
    c2.join()
    c3.join()


main()

感谢任何帮助。我真的很茫然。

1 个答案:

答案 0 :(得分:0)

当线程中的代码获取信号量时,它应该随后释放相同的信号量。所以而不是:

items.acquire()
...
free.release()

您的代码必须这样做,例如

items.acquire()
...
items.release()
相关问题