python2.6 tornado-4.2-py26環境
import tornado.ioloop
finish() call twice 示例**:需注意執行緒拋的異常,主線程是catch不到的import tornado.web
from tornado.web import asynchronous
from concurrent import futures
executor = futures.threadpoolexecutor(max_workers=2)
def call(handler):
handler.write("hello, world!")
handler.finish() # 如果不寫這行則回掛住
class mainhandler(tornado.web.requesthandler):
@asynchronous
def get(self):
executor.submit(call, self)
(r"/", mainhandler),
])
if __name__ == "__main__":
tornado.ioloop.ioloop.current().start()
~
import tornado.ioloop
import tornado.web
from tornado.web import asynchronous
from concurrent import futures
executor = futures.threadpoolexecutor(max_workers=2)
import time
import traceback
def call(handler):
try:
print id(handler)
handler.write("hello, world! id: %s" % id(handler))
time.sleep(5)
handler.finish()
print "over.id[%s]" % id(handler)
except:
print traceback.format_exc()
class mainhandler(tornado.web.requesthandler):
#@asynchronous
def get(self):
executor.submit(call, self)
(r"/", mainhandler),
])
if __name__ == "__main__":
tornado.ioloop.ioloop.current().start()
另外注意如果使用tornado.ioloop.ioloop.instance().add_callback(lambda: handler.finish()) 返回值最好是字串, 編碼如果出現問題,則使用者不會呼叫到finish,原始碼如下:
def write(self, chunk):if self._finished:
raise runtimeerror("cannot write() after finish()")
if not isinstance(chunk, (bytes, unicode_type, dict)):
message = "write() only accepts bytes, unicode, and dict objects"
if isinstance(chunk, list):
message += ". lists not accepted for security reasons; see "
raise typeerror(message)
if isinstance(chunk, dict):
chunk = escape.json_encode(chunk) # 這裡會報 'utf8' codec can't decode bytes
chunk = utf8(chunk)
DataTable多執行緒操作報錯情況
最近在寫乙個http介面時用了datatable這個強大的利器,介面用瀏覽器跑起來沒任何問題。當時也沒考慮併發問題,後來用乙個壓力測試工具做大併發測試,1000 s次速度測試。發現程式報錯了。程式報錯了第一反應還是去檢查 是不是 出現問題。發現邏輯都是對的,然後用瀏覽器開啟介面,發現一切ok 然後心...
多執行緒版本的RunTime Library
1 unsigned long beginthreadex void security,相當於security引數 unsigned stack szie,新執行緒的堆疊大小,以位元組為單位 unsigned stdcall start address void 執行緒啟動時所執行的函式。對應的wi...
tulip 多執行緒的版本
上次的網路程式設計的例子,改寫成多執行緒的是這樣 import socket import thread def main listen sock socket.socket family socket.af inet,type socket.sock stream,proto socket.ipp...