How do I close the flow?

I’ve been experimenting with the threading library
I wrote something like this:

def active():
thread = threading.Thread(target=active)

Now, whatever code I run is output infinity a:

How do I close the flow? (Just in case, I use Google Colab)

There is no problem with the code that you wrote here.

In the picture, you have different code, with a while loop. But there is also no problem with it. I typed it out and ran it. As expected, I saw False 4 times, and then it stopped.

But if you add a while loop without using the stop flag system, you will get stuck.

It is not possible to make the thread stop “from outside” in a proper or safe way. This is because there might only be certain times when it’s okay to stop (for example, in the middle of a calculation, some objects could be in an invalid state). Only the thread’s own logic can know when to stop.

You need to use some kind of signal to tell the thread that you want it to stop, and then the thread’s logic must check for that signal and finish its work. Only then, the join method can wait for the thread itself to stop. This is how the stop global works in the code in the picture. If you start fresh with that, you should see it works properly. (Perhaps you noticed, the infinite output shows a, but there is nothing like print("a") in the code from the picture.)

It’s possible that Colab gets confused between two different versions of the code. I’ve never used it, so I don’t know anything about how it works. Maybe it’s still running a wrong version of the code and you need to use something else to force it to stop (like how Ctrl-C will cause a KeyboardInterrupt in the terminal).

1 Like