简体   繁体   English

生产者使用者3个线程,每个在python中

[英]Producer consumer 3 threads for each in python

I'm trying to do a producer consumer program. 我正在尝试制作生产者消费者程序。 I got it working just fine with one thread for each and I'm trying to modify it to run three threads of each. 我让每个线程都可以正常工作,并且我试图将其修改为每个线程都运行三个线程。 It appears that each of the consumer threads is trying to consume each released item. 似乎每个使用者线程都在尝试消耗每个已发布的项目。

# 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()

Any help is appreciated. 任何帮助表示赞赏。 I'm really at a loss with this one. 我真的很茫然。

When your code in a thread acquires a semaphore, it should then subsequently release the same semaphore. 当线程中的代码获取信号量时,它随后应释放相同的信号量。 So instead of: 所以代替:

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

your code must do, eg 您的代码必须做的事,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM