Python3中的多线程技术

6
我在使用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')
1个回答

8

我认为较新的线程模块更适合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中的thread.start_new_thread发生了什么https://www.tutorialspoint.com/python3/python_multithreading.htm


1
当您说线程模块更强大时,您能否提供更多细节? - shiv455
_thread 用于低级别的线程处理。在 threading 模块中还有其他方法,也包含实现线程处理的 Thread 类。如果您查看我提供的教程,它会详细介绍 _thread 和 threading 之间的区别。 - Zx4161

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接