简体   繁体   中英

Python 2: Thread stops running and I don't know why

I am trying to have a thread run in the background that loops that I can turn off with a gui button that sets the go property of the Thread object to false. However the thread only runs for a split second.

    class MyThread(threading.Thread):
            def __init__(self):
                    threading.Thread.__init__(self)
                    self.go = True
            def run(self):
                    while self.go:
                            print "okay!"

This should continuously print "okay!" but it doesn't. At first it does nothing. Then when I press the gui button to stop it and then start another instance of MyThread it then prints about 50 lines and stops.

I am running Ubuntu Linux 11.04 with python 2.7.1

Remember that in python all threads (that use the interpreter) are subject to the GIL, and so there is only ever one thread running python code at any time. This means that if you have a busy loop in python land holding the GIL in one thread, it will stop execution of another thread. To read more about the GIL, have a look at David Beazley's presentations here: http://www.dabeaz.com/GIL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM