python3中的多线程

标签 multithreading python-3.x flask

我在 python 中使用多线程和 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')

最佳答案

我认为较新的模块线程将更适合 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 来实现向后兼容性。与您的代码的效率没有特别相关,但无论如何都很高兴知道。

What happened to thread.start_new_thread in python 3https://www.tutorialspoint.com/python3/python_multithreading.htm

关于python3中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50987408/

相关文章:

java - 在静态方法中创建新的 JAXB Marshaller 实例...它是线程安全的吗?

python - python 类中的所有方法都表现得像静态

python - sqlalchemy.exc.ProgrammingError : (psycopg2. 编程错误)关系 "story"不存在

python - 使用 Python + Flask-SqlAlchemy 的默认查询范围

java - 安卓开发 : How do I integrate threads in this?

java - Java 中的线程组

java - 如果对 int 变量的写入和读取是原子的,为什么需要 AtomicInteger?

python - 为什么 for 循环不遍历我所有的 readlines?

python-3.x - 如何使用 matplotlib/python 绘制 ROC 曲线

pythonanywhere 404错误