-1

I want to use threads in python. My first idea was to implement 3 threads with one queue as global between them. One of the threads uses as show the elements of the queue and others fill the queue in different time slots. But when I run the code, only the first thread work and others don't print anything!

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()
ChristianYami
  • 586
  • 1
  • 9
  • 17
ajapyy
  • 1
  • 1
  • The threading module is quite low-level, you might want to use a different library. – AMC Mar 20 '20 at 15:33

1 Answers1

0

This line:

t = threading.Thread(target=add(), name="t")

particularly add(), simply calls the add function and then passes the result as the target argument. But the add() function never completes, so it doesn't even get as far as trying to call the Thread constructor.

Pass the function object add without calling it.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89