0

I am having trouble with stopping a looping thread. I use an event to stop the loop but the output is different than I expected. I wrote the following code

import threading 
from time import sleep

class foo(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.stop_event = threading.Event()

    def run(self):
        while not self.stop_event.is_set():
            print('1')
            sleep(1)
            print('2')
            sleep(1)
        print('done')

class bar(threading.Thread):
    def __init__(self):
       threading.Thread.__init__(self)
       self.run_thread()


    def run_thread(self):
       th1 = foo()
       th1.start()
       sleep(4)
       th1.stop_event.set()

prgm = bar()
prgm.run_thread()

Gives me the output:

1
2
1
2
1
done
2
1
2
done

I expected the word 'done' to be printed onces when the while loop ends. But for some reason 'done' is printed twice. Am I using Events wrong or is the thread started multiple times?

1
  • I added print(''hallo') before the while (inside the thread). The output prints "hallo" twice. So for some reason the thread is started twice. Commented Mar 23, 2017 at 20:12

2 Answers 2

1

You already do self.run_thread() in the constructor of bar (i.e. bar.__init__):

class bar(...):
    def __init__(self):
       threading.Thread.__init__(self)

       # !!!!
       self.run_thread()

So, when you create an instance of bar:

stuff = bar()

You're executing bar.run_thread as well. Your current code executes this function twice:

prgm = bar() # executed here
prgm.run_thread() # and here

As a result, you get some unexpected behavior.

Sign up to request clarification or add additional context in comments.

1 Comment

Oops. Thanks for the answer
0

Missing two points:

  1. Add if __name__ == '__main__': before prgm = bar()
  2. Add sleep(0.1)A before each run...

1 Comment

How would adding "if name == 'main':" improve the code? Other than improving the overall 'design' of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.