Jacob Gravesen
Jacob Gravesen

Reputation: 11

Threading In Python: Parralel While True Loops

I'm trying to run a test where two while True loops are running side by side.

The first loop prints "Haha", the other is supposed to print "Coffee".

But it seems that the code gets stuck in the first loop, and thus never starts the two threads.


A similar issue was posted here: Python Threading: Multiple While True loops

But the solution doesn't seem to help me.


Here is the code snippet:

def haha_function():
    while True:
        print("Haha")
        time.sleep(0.5)

def coffee_function():
    while True:
        print("Coffee")
        time.sleep(0.5)

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function, daemon=True)
        thread1.start()
        thread1.join()

        thread2 = threading.Thread(target=coffee_function, daemon=True)
        thread2.start()
        thread2.join()

When the function do_something is run, the terminal only prints "Haha", rather than alternating between "Haha" and "Coffee".

Upvotes: 1

Views: 557

Answers (1)

rcshon
rcshon

Reputation: 927

thread1.join() blocks the main thread to wait for the thread to finish. But it never does since its a while True loop. You can call the join after starting the second thread.

class DummyScreen3(Screen, threading.Thread):

    def do_something(self):
        thread1 = threading.Thread(target=haha_function)
        thread1.start()

        thread2 = threading.Thread(target=coffee_function)
        thread2.start()

Also, I don't understand why you are inheriting from threading.Thread but I'll leave it as it is...

EDIT: Removed daemon=True and .join() since the functions called are never-ending.

Upvotes: 3

Related Questions