【问题标题】:Multithreading in python3python3中的多线程
【发布时间】:2018-06-22 11:56:02
【问题描述】:

我在带有 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')

【问题讨论】:

    标签: multithreading python-3.x flask


    【解决方案1】:

    我认为较新的模块线程会更适合 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 3和https://www.tutorialspoint.com/python3/python_multithreading.htm

    【讨论】:

    • 你说线程模块更强大的时候能提供更多细节吗
    • _thread 用于低级线程。 threading 模块中还有其他方法,还包含实现线程的 Thread 类。如果你去看我提供的那个教程,它会详细介绍 _thread 和 threading 之间的区别
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2018-04-01
    • 2022-01-16
    相关资源
    最近更新 更多