像這樣的東西應該工作:
import threading
import time
from tornado import web
from tornado.ioloop import IOLoop
lock = threading.Lock()
is_processing = False
def background_process():
global is_processing
with lock:
is_processing = True
# You should never call sleep within a Tornado request handler, but it's ok
# on a background thread.
time.sleep(10)
with lock:
is_processing = False
class MyHandler(web.RequestHandler):
def get(self):
with lock:
p = is_processing
if p:
self.write("Please try again")
else:
t = threading.Thread(target=background_process)
t.start()
self.write("Started processing")
def make_app():
return web.Application([
(r"/", MyHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
IOLoop.current().start()
鎖是不是在這段代碼實際上必要的,因爲「is_processing」是一個簡單的布爾。如果你需要更復雜的數據結構來控制後臺處理器,我已經包含了鎖,我想告訴你如何鎖定對數據結構的訪問。