我正在使用python2.7并安装了futures模块。在
我尝试在tornado中使用ThreadPoolExecutor实现多线程。在
这是我实现的代码。在
from __future__ import absolute_import
from base_handler import BaseHandler
from tornado import gen
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
from bson.objectid import ObjectId
from spark_map import Map
from concurrent import futures
import tornado
class MapService(BaseHandler):
MapDB = dict()
executor = futures.ProcessPoolExecutor(max_workers=3)
@tornado.web.asynchronous
@gen.coroutine
@post(_path='/map', _type=[str, str])
def postMap(self, inp, out):
db = self.settings['db']
function = lambda (x,y): (x,y[0]*2)
future = yield db.MapInfo.insert({'input': inp, 'output': out, 'input_function': str(function)})
response = {"inserted ID": str(future)}
self.write(response)
m = Map(inp, out, function, appName=str(future))
futuree = self.executor.submit(m.operation())
self.MapDB[str(future)] = {'map_object': m, 'running_process_future_object': futuree}
self.finish()
@tornado.web.asynchronous
@gen.coroutine
@delete(_path='/map/{_id}', _types=[str])
def deleteMap(self, _id):
db = self.settings['db']
future = yield db.MapInfo.find_one({'_id': ObjectId(_id)})
if future is None:
raise AttributeError('No entry exists in the database with the provided ID')
chk = yield db.MapInfo.remove(future)
response = { "Succes": "OK" }
self.write(response)
self.MapDB[_id]['map_object'].stop()
del self.MapDB[_id]
self.finish()
在上面的代码中,我使用post请求inp和out接收两个输入。然后我和他们一起做手术。此操作应持续到收到停止并删除进程的删除请求。在
我面临的问题是多个请求。它只执行第一个请求,而其他请求则等待第一个请求完成,从而阻塞主IOLoop。在
所以,我想在一个单独的线程中运行每个进程。我应该如何实施?在
似乎
m.operation()
正在阻塞,因此需要在线程上运行它。这样做的方式会在调用m.operation()
时阻塞主线程,并在之后生成一个线程:相反,您希望将函数传递给将执行该函数的线程:
^{pr2}$没有帕伦斯。在
相关问题 更多 >
编程相关推荐