shi*_*455 4 multithreading flask python-3.x
我在python3中使用多线程与Flask如下.想知道下面的代码是否有任何问题,如果这是使用线程的有效方法
import _thread
COUNT = 0
class Myfunction(Resource):
@staticmethod
def post():
global GLOBAL_COUNT
logger = logging.getLogger(__name__)
request_json = request.get_json()
logger.info(request_json)
_thread.start_new_thread(Myfunction._handle_req, (COUNT, request_json))
COUNT += 1
return Response("Request Accepted", status=202, mimetype='application/json')
@staticmethod
def _handle_req(thread_id, request_json):
with lock:
empID = request_json.get("empId", "")
myfunction2(thread_id,empID)
api.add_resource(Myfunction, '/Myfunction')
Run Code Online (Sandbox Code Playgroud)
我认为较新的模块线程更适合python 3.它更强大.
import threading
threading.Thread(target=some_callable_function).start()
Run Code Online (Sandbox Code Playgroud)
或者如果你想传递参数
threading.Thread(target=some_callable_function,
args=(tuple, of, args),
kwargs={'dict': 'of', 'keyword': 'args'},
).start()
Run Code Online (Sandbox Code Playgroud)
除非您特别需要_thread以实现向后兼容性.与您的代码的效率无关,但无论如何都很好.
看看python 3中的thread.start_new_thread发生了什么,https://www.tutorialspoint.com/python3/python_multithreading.htm
| 归档时间: |
|
| 查看次数: |
9698 次 |
| 最近记录: |