Python 使用多线程和一个队列

Python 使用多线程和一个队列,python,multithreading,Python,Multithreading,我想在python中使用线程。 我的第一个想法是实现3个线程,其中一个队列作为它们之间的全局队列。其中一个线程使用as来显示队列的元素,其他线程则在不同的时隙中填充队列。但是当我运行代码时,只有第一个线程工作,其他线程不打印任何内容 import queue import time import threading q = queue.Queue() w = threading.Lock() def add(): i=1 while True: i*=2 w.

我想在python中使用线程。 我的第一个想法是实现3个线程,其中一个队列作为它们之间的全局队列。其中一个线程使用as来显示队列的元素,其他线程则在不同的时隙中填充队列。但是当我运行代码时,只有第一个线程工作,其他线程不打印任何内容

import queue
import time
import threading

q = queue.Queue()
w = threading.Lock()

def add():
    i=1
    while True:
    i*=2
    w.acquire()
    q.put(i)
    w.release()
    print("add done")
    time.sleep(.5)

def mul():
    i=1
    while True:
    i+=1
    w.acquire()
    q.put(i)
    w.release()
    print("mul done")
    time.sleep(.7)

def show():
    while True:
        while not q.empty():
            print("buffer data =  ", q.get)

if __name__ == "__main__":

    t = threading.Thread(target=add(), name="t")
    t.setDaemon(True)
    t.start()
    r = threading.Thread(target=mul(), name="r")
    r.setDaemon(True)
    r.start()
    s = threading.Thread(target=show(), name="show")
    s.setDaemon(True)
    s.start()

    t.join()
    r.join()
    s.join()
这一行:

t = threading.Thread(target=add(), name="t")
尤其是
add()
,只需调用
add
函数,然后将结果作为目标参数传递。但是
add()
函数从未完成,因此它甚至没有尝试调用
线程
构造函数


传递函数对象
add
,而不调用它。

线程模块非常低级,您可能需要使用其他库。