2
import threading
import time

class Eat(threading.Thread):
    def __init__(self, surname):
        self.counter = 0
        self.surname = surname
        threading.Thread.__init__(self)

    def run(self):
        while True:
            print("Hello "+self.surname)
            time.sleep(1)
            self.counter += 1
            print("Bye "+self.surname)

begin = Eat("Cheeseburger")
begin.start()

while begin.isAlive():
    print("eating...")

While begin is in process of "eating", I want to print "eating..." but it seems i'm stuck in an infinite loop even after 1 second. Why do I get stuck in an infinite loop?

Jürgen Paul
  • 14,299
  • 26
  • 93
  • 133

3 Answers3

4

It is in an infinite loop because you put an infinite loop into run:

def run(self):
    while True:

A fixed version might look like this:

def run(self):
    print("Hello "+self.surname)
    time.sleep(1)
    self.counter += 1
    print("Bye "+self.surname)
themel
  • 8,825
  • 2
  • 32
  • 31
0

well.. not sure about everything else, but you are using begin.start() instead of begin.run() and regardless, begin is a horrible name for a class.

running it with run() gives this output:

>>> 
Hello Cheeseburger
Bye Cheeseburger

and then it continues to infinity with hello...bye...hello..bye.. over and over...

might help if you provide a desired output.

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
0

You have two loops in your program,

one in the thread:

while True:
    print("Hello "+self.surname)
    time.sleep(1)
    self.counter += 1
    print("Bye "+self.surname)

and one in the main program:

while begin.isAlive():
    print("eating...")

the thread will always be alive because you have a while true loop within it, which has no ending.

thus the thread in your main program will also be infinite because it will always be waiting for the loop in the thread to finish, which it wont.

you will have to either put a limit on the loop within the thread, like so:

while self.counter < 20:
    print("Hello "+self.surname)
    time.sleep(1)
    self.counter += 1
print("Bye "+self.surname)

or take out the loop entirely. This will stop the main program from becoming stuck waiting for the threads loop to end and fix both infinite loops.

Serdalis
  • 10,296
  • 2
  • 38
  • 58