While loop in Threads

Viewed 2428

I am trying to use while loops inside threads for a bigger project. For simplicity I created an easier example to test it, but it doesn`t work.

My goal is to control the thread for the main function and when the variable go_thread_one is switched to False the thread should end. At the moment the second thread is not being used and only the first thread print its text.

How can I fix this error?

Below is the simplified version of my code:

import time
from threading import Thread

go_thread_one = True


def first_thread():
    while go_thread_one:
        print('Thread 1')
        time.sleep(0.5)


def second_thread():
    print('Thread 2')


if __name__ == "__main__":
    t1 = Thread(target=first_thread())
    t2 = Thread(target=second_thread())

    t1.daemon = True
    t2.daemon = True

    t1.start()
    t2.start()
    time.sleep(2)

    go_thread_one = False

    print("end main Thread")
1 Answers

First of all, there is a problem in these lines:

t1 = Thread(target=first_thread())
t2 = Thread(target=second_thread())

You should pass a callable object to the Thread, but instead you call a function and pass its result. So you don't even create a t1, but go inside first_thread function and loop there forever.

To fix this, change Thread creation to:

t1 = Thread(target=first_thread)
t2 = Thread(target=second_thread)

Next, the

go_thread_one = False

will not give a desired effect – main thread will finish after time.sleep(2) even without this line.

To deal with it, you can add

t1.join()
t2.join()
Related