0

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.

4
  • 3
    task = threading.Thread(target=mock_app_handler) # don't call the function there, instead pass the function object. Also you don't need the args there, since the function doesn't take any arguments Commented May 29, 2021 at 18:18
  • @hansolo Thanks. My bad. Didn't realize it until now. Worked now. Commented May 29, 2021 at 18:20
  • @hansolo add this as an answer. I will accept it. Commented May 29, 2021 at 18:50
  • Sure. Thanks :) Commented May 29, 2021 at 18:54

1 Answer 1

2

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.

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

1 Comment

My code is a stripped-down version of the actual code. The actual code has args to be passed. Thanks.

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.