Skip to content

Instantly share code, notes, and snippets.

@zhangkaizhao
Last active April 25, 2018 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkaizhao/4f66fa6947b8ed0f29e61b6f18e343d0 to your computer and use it in GitHub Desktop.
Save zhangkaizhao/4f66fa6947b8ed0f29e61b6f18e343d0 to your computer and use it in GitHub Desktop.
using tornado ioloop in multiple threads
import random
import threading
import time
import tornado.gen
import tornado.ioloop
@tornado.gen.coroutine
def _work(i):
count = random.randint(1, 10)
print("Thread {} count: {}".format(i, count))
for _ in range(count):
print("Thread {} working...".format(i))
yield tornado.gen.sleep(0.1)
ioloop = tornado.ioloop.IOLoop().current()
print("Thread {} ident: {}".format(i, threading.get_ident()))
ioloop.stop()
print("Thread {} done.".format(i))
def work(i):
ioloop = tornado.ioloop.IOLoop().current()
print("Thread {} ident: {}".format(i, threading.get_ident()))
_work(i)
ioloop.start()
print(i, ioloop)
def main():
workers = []
for i in range(3):
worker = threading.Thread(target=work, args=(i,))
worker.setDaemon(True)
workers.append(worker)
for worker in workers:
worker.start()
for worker in workers:
worker.join()
if __name__ == '__main__':
main()
$ python3 app.py
Thread 2 ident: 140376056444672
Thread 2 count: 1
Thread 2 working...
Thread 0 ident: 140376073230080
Thread 1 ident: 140376064837376
Thread 0 count: 7
Thread 1 count: 6
Thread 0 working...
Thread 1 working...
Thread 1 working...
Thread 0 working...
Thread 2 ident: 140376056444672
Thread 2 done.
2 <tornado.platform.epoll.EPollIOLoop object at 0x7fabdb69fc50>
Thread 1 working...
Thread 0 working...
Thread 1 working...
Thread 0 working...
Thread 1 working...
Thread 0 working...
Thread 1 working...
Thread 0 working...
Thread 0 working...
Thread 1 ident: 140376064837376
Thread 1 done.
1 <tornado.platform.epoll.EPollIOLoop object at 0x7fabdb69fba8>
Thread 0 ident: 140376073230080
Thread 0 done.
0 <tornado.platform.epoll.EPollIOLoop object at 0x7fabdd9419e8>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment