Python: How to access a Blocking Function Dynamically?

In this, we will learn How to access a blocking function dynamically in python where we need to use concurrent. future module for creating a thread pool and then submitting tasks to it. And moreover, it allows you to keep running the blocking function asynchronously, which does not block the main process.


Python  Blocking Function

Here we have given an example that shows how we can get the blocking function to run and understand how it works with the example of pseudo code.

import concurrent. futures
import time

def blocking_ function(n):
    print(f' Starting task {n}')
    time. sleep(5)
    print(f' Finishing task {n}')

# Create a thread pool with 2 workers
with concurrent. futures.ThreadPool Executor( max_ workers=2) as executor:
    # Submit tasks to the thread pool
    futures = [executor. submit( blocking_ function, i) for i in range(5)]

    # Wait for tasks to complete and retrieve results
    results = [f. result() for f in futures]

print(' All tasks completed')

In the above given example of code, we had defined a blocking function named as blocking function that is used for taking arguments as n and sleeping it for n seconds here it is 5 seconds before printing the actual output. Here we also created a thread pool executor which has two workers and submit 5 tasks to it, which is done by submit function.

Here submit function returns a future object which is used for representing the result, the result of the submitted which was previously stored in the list as future.

Here when we wait for completion and get the result using the result method which was defined in the object future, And finally we print a message which is used for showing that all tasks have been completed.

Here we run a blocking function asynchronously in a dynamic way and without blocking the main process. Here we can edit the number of workers in the thread pool for controlling the degree of parallelism and we can submit the task as dynamically as needed.


To learn more about How to access a Blocking Function Dynamically in python visit: Accessing Blocking function dynamically.

To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

To learn more about different other programming languages like java, MySQL, MongoDB, and other language solutions visit: beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: