Home > database >  How can I make one thread sleep while the others run in python
How can I make one thread sleep while the others run in python

Time:03-25

I'm new to multithreading, and have been trying to make a timer in the background for one of my programs while several other threads execute their code. I currently have my code set up like this:

def timer(length):
    global kill
    kill = False
    print('Timer starting!')
    for i in range(length):
        time.sleep(1)
    kill = True

def r(interval, id):
    print(id, "running")
    while True:
        if kill:
            break
        time.sleep(interval)
        print(f'{id}: {time.localtime()}')

timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))

threads = [timerThread, runThread1, runThread2]

timerThread.start()
runThread1.start()
runThread2.start()

for t in threads:
    t.join()

Obviously, it's not a useful program (only meant to help me learn the basics of the threading module), but I still need to know how to fix this. I'm 95% sure the issue is caused by using "time.sleep(1)" in the timer function, but I don't know an alternative to use that would only affect one thread. I'd appreciate any suggestions.

CodePudding user response:

You're calling your functions before you even create the thread:

timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))

You need to pass a callable target rather than the result of having already called it; the args can be passed separately:

timerThread = threading.Thread(target=timer, args=(15,))
runThread1 = threading.Thread(target=r, args=(2, "thread1"))
runThread2 = threading.Thread(target=r, args=(5, "thread2"))
  • Related