tornado icon indicating copy to clipboard operation
tornado copied to clipboard

IOLoop become current loop issue

Open yuxizhou opened this issue 11 years ago • 3 comments

In version 4.1, when a new IOLoop is created, it automatically becomes “current” for the thread if there is not already a current instance.

so, if I instance an IOLoop before application.listen(8888), HttpServer will add this socket into the IOLoop I instance before. finally I run "tornado.ioloop.IOLoop.instance().start()", socket is NOT added into this "main loop".

import tornado.ioloop
import tornado.web

_ioloop = tornado.ioloop.IOLoop()

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

yuxizhou avatar May 06 '15 08:05 yuxizhou

You're not the only one to have trouble with this; see #1390.

I know this is just an example, but in your real code why did you create one IOLoop and then start a different one? Was the IOLoop represented here by _ioloop started in a different thread?

There are a couple of workarounds, the simplest of which would be to call IOLoop.instance().make_current() at the start of the __main__ block. In 4.2 you'll also be able to pass make_current=False when constructing _ioloop.

I'm considering reversing the decision to make new IOLoops current automatically since it has tripped up a few people, but it does seem to me to be an improvement overall.

bdarnell avatar May 07 '15 03:05 bdarnell

I use HttpClient before start main loop, I instance main loop before Instance HttpClient to make it right

yuxizhou avatar May 07 '15 04:05 yuxizhou

FYI the synchronous HTTPClient will be fixed in 4.2; it uses the make_current=False flag to avoid interfering with the regular IOLoop.

You can also use the pattern in this message to use AsyncHTTPClient while starting up: https://groups.google.com/d/msg/python-tornado/Zw5Xd8YVAVk/Rq4ZzbvxUw4J

bdarnell avatar May 07 '15 13:05 bdarnell