5

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')
shiv455
  • 7,384
  • 19
  • 54
  • 93

1 Answers1

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

Zx4161
  • 180
  • 8
  • 1
    can you provide more details when you say threading module is more powerful – shiv455 Jun 22 '18 at 14:16
  • _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 – Zx4161 Jun 22 '18 at 14:42