tornado thread 任务处理模式

import functools
import time
import threading
import logging
import Queue
#import hunspell

import tornado.web
import tornado.websocket
import tornado.locale
import tornado.ioloop
from tornado.options import define, options

define('debug', type=bool, default=False, help='run in debug mode with autoreload (default: false)')

class Handler(tornado.web.RequestHandler):
    @property
    def queue(self):
        return self.application.queue

    @tornado.web.asynchronous
    def get(self, word):
        self.queue.put( (word, self.on_callback) )

    def on_callback(self, output):
        self.write("Thread output: %s" % output)
        self.finish()

class ThreadWord(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
        #self.hobj = hunspell.HunSpell('./fr-classique.dic', './fr-classique.aff')

    def run(self):
        while True:
            try:
                word, callback = self.queue.get(True, 1)
            except Queue.Empty:
                continue
            # cpu intensive work ...
            #output = self.hobj.spell(word)
            output = word
            tornado.ioloop.IOLoop.instance().add_callback(functools.partial(callback, output))
            self.queue.task_done()

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/(.*)", Handler),
        ]
        settings = {
            'cookie_secret': 'W/wT5ndaR/2sa3m8OOQ5q0xDvnZclE4BtimO1f+QM2Y=',
            'debug':options.debug,
        }
        tornado.web.Application.__init__(self, handlers, **settings)

        self.queue = Queue.Queue()

        for i in range(5):
            t = ThreadWord(self.queue)
            t.setDaemon(True)
            t.start()

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值