Search code examples
pythonpython-3.xmultithreadingpython-multithreading

Python Thread running asynchronously


I am trying to run the below code expecting it to run asynchronously.

import threading
import time


def mock_app(widgets=None, filters=None):
    print('Mock app called')
    task = threading.Thread(target=mock_app_handler(), args=())
    task.start()
    print('Thread spawned')
    return "success"


def mock_app_handler():
    # do something
    print('doing something')
    time.sleep(2)
    print('done something')


print(mock_app())

But, the code is executing synchronously. I am getting the below result.

Mock app called
doing something
done something
Thread spawned
success

Why is this happening? Am I missing something?

UPDATE: I tried setting task.daemon = True. That didn't work either.


Solution

  • The problem was, you were calling the function mock_app_handler instead of passing the function object. The target in threading.Thread expects a callable. So

    Instead of

    task = threading.Thread(target=mock_app_handler(), args=())
    

    Use

    task = threading.Thread(target=mock_app_handler)
    

    Also you don't need to pass the empty args, since the function mock_app_handler doesn't need any args.