1

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".

  • 1
    you should call `thread1.join()` after starting the second thread – rcshon Apr 19 '22 at 13:09
  • 2
    There's no point in calling join() on either of the threads because they'll never terminate other than upon receipt of some destructive signal – DarkKnight Apr 19 '22 at 13:15

1 Answers1

3

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.

rcshon
  • 907
  • 1
  • 7
  • 12
  • Ditto what Lancelot said: There is no reason to `join()` a thread that never ends. A better solution to OP's problem would be to remove both of the `join()` statements, and also remove `daemon=True` from both of the `Thread(...)` constructor calls. – Solomon Slow Apr 19 '22 at 14:24
  • @Solomon Slow You're right. there's no reason to call join on a never-ending thread in Python, and also no reason to make it a daemon thread here. I merely reordered the operations to make it work in haste. I'll update my answer. – rcshon Apr 19 '22 at 14:54
  • Thanks a lot for the answers, it solved the problem! I removed the daemon=True parameter and the inheritence from threading in the class as well. – Jacob Gravesen Apr 20 '22 at 06:44