tornado一步一步来(二)

单个进程异步

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
# tornado io_loop是单线程任务,
# 当任何堵塞代码加入到该线程中都会导致整体堵塞.
# 所以必须要谨慎对待ioloop.
import time
import functools
import tornado.concurrent
from tornado import gen, ioloop


def fibonacci(n):
    if n <= 1:
         return 1
    else:
         return fibonacci(n-1) + fibonacci(n-2)


def proxy(pool):
    return pool.submit(fibonacci, 34)


def main():

    pool = tornado.concurrent.futures.ProcessPoolExecutor()

    def callback(future):
        """
        io_loop执行完proxy()后会将执行结果的future
        返回给本函数并且运行本函数
        """
        while not future.result().done():
            # 查看运行状态.
            print future.result()
            time.sleep(0.5)
        print "i'm exiting."

    future = gen.Future()
    future.set_result(proxy(pool))
    io_loop.add_future(future, callback=callback)
    print 'hello'


if __name__ == '__main__':
    io_loop = ioloop.IOLoop.current()
    io_loop.run_sync(main)

 

进程池异步

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
# tornado io_loop是单线程任务,
# 当任何堵塞代码加入到该线程中都会导致整体堵塞.
# 所以必须要谨慎对待ioloop.
import time
import tornado.concurrent
from tornado import gen, ioloop
import multiprocessing as mp


def fibonacci(n):
    print mp.current_process().name
    if n <= 1:
         return 1
    else:
         return fibonacci(n-1) + fibonacci(n-2)


@gen.coroutine
def proxy(pool):
    s = pool.submit(fibonacci, 10)
    raise gen.Return(s)


def main():

    pool = tornado.concurrent.futures.ProcessPoolExecutor()

    def callback(future):
        """
        io_loop执行完proxy()后会将执行结果的future
        返回给本函数并且运行本函数
        """
        while not future.result().done():
            # 查看运行状态.
            print future.result()
            time.sleep(0.5)
        print "i'm exiting.", dir(future.result())

    for i in range(100):
        io_loop.add_future(proxy(pool), callback=callback)

    # 这里将会第一个输出到屏幕中, 也就是说, 上面的代码已经执行并且仍在计算中, 但是不会堵塞.
    print 'hello'      


if __name__ == '__main__':
    io_loop = ioloop.IOLoop.current()
    io_loop.run_sync(main)

 

你可能感兴趣的:(tornado一步一步来(二))