【问题标题】:Producer consumer 3 threads for each in pythonpython中的每个生产者消费者3个线程
【发布时间】:2015-10-16 11:35:10
【问题描述】:

我正在尝试做一个生产者消费者程序。我让它工作得很好,每个线程都有一个线程,我正在尝试修改它以运行每个线程的三个线程。似乎每个消费者线程都在尝试使用每个已发布的项目。

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

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

【问题讨论】:

    标签: python multithreading semaphore


    【解决方案1】:

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

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

    你的代码必须做,例如

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

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多