multithreading - python3中的多线程
问题描述
我在带有 Flask 的 python3 中使用多线程,如下所示。想知道下面的代码是否有任何问题,以及这是否是使用线程的有效方式
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')
解决方案
我认为较新的模块线程将更适合 python 3。它更强大。
import threading
threading.Thread(target=some_callable_function).start()
或者如果你想传递参数
threading.Thread(target=some_callable_function,
args=(tuple, of, args),
kwargs={'dict': 'of', 'keyword': 'args'},
).start()
除非您特别需要 _thread 来实现向后兼容性。与您的代码的效率没有特别相关,但无论如何都很高兴知道。
请参阅python 3和https://www.tutorialspoint.com/python3/python_multithreading.htm中的 thread.start_new_thread 发生了什么
推荐阅读
- networkx - 通过 for 循环的路线的单独颜色
- javascript - 当另一个打开时如何关闭手风琴?
- c++ - 在不使用虚拟继承的情况下继承接口的最佳方法是什么?
- c++ - *(iterator) 和 *(++iterator) 在下面的 c++ 代码中是什么意思?
- javascript - 减少将数组转换为唯一数组属性
- ssh - 修复 tput:使用 SSH 运行远程 shell 脚本时没有指定 $TERM 的值和没有指定 -T
- ios - 通过 TOR swift 路由 WKWebView
- python - 日期时间格式 Python 的用户输入
- php - 在另一个文件中调用函数
- android - ExoPlayer 下载后从缓存/离线播放文件