ThreadPoolExecutor submit not return immedetiely

Viewed 1855

I'm creating the asynchronous function call in my application to process the task(function).

I have tried with threadpoolexecutor as shown below for asynchronous call but it is not working as expected, kindly let me know What I have done wrongly?

class MainTest:

    def __init__(self): pass


    def show_msg(self):
        print('inside show msg function..!')
        time.sleep(3)

    def executor_call(self):
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
        executor.submit(obj.show_msg())
        executor.shutdown(wait=False)
        print('Hi')

obj = MainTest()

obj.executor_call()

I am expecting above code output like

Hi

inside show msg function..!

but I am getting

inside show msg function..!

Hi
1 Answers

You're calling your function immediately instead of executing it through the ThreadPoolExecutor. This line:

executor.submit(obj.show_msg())

Is functionally equivalent to:

result = obj.show_msg()
executor.submit(result)

What ThreadPoolExecutor.submit() expects from you is to pass it a callable which it will execute in a separate thread, so change the call to:

executor.submit(obj.show_msg)

That being said, even when you fix it, you still won't be getting your expected behavior unless you move your time.sleep(3) before printing of your message in the show_msg() function.

Also, keep in mind that using threads does not give you parallel execution, it gives you concurrent execution for all things happening within the Python realm (system calls like I/O can happen in parallel) due to the dreaded GIL. You'll need to employ multiprocessing if you want a proper parallel execution.

Related