6

im using multithreading in python3 with Flask as below. Would like to know if there is any issue in below code, and if this is efficient way of using threads

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 Answer 1

8

I think the newer module threading would be better suited for python 3. Its more powerful.

import threading

threading.Thread(target=some_callable_function).start()

or if you wish to pass arguments

threading.Thread(target=some_callable_function,
    args=(tuple, of, args),
    kwargs={'dict': 'of', 'keyword': 'args'},
).start()

Unless you specifically need _thread for backwards compatibility. Not specifically related to how efficient your code is but good to know anyways.

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

Sign up to request clarification or add additional context in comments.

2 Comments

can you provide more details when you say threading module is more powerful
_thread is for low level threading. There's additional methods in the threading module and also contains the Thread class that implements threading. If you go to that tutorial I supplied it goes into details on the differences between _thread and threading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.