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 concurrently. 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

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. which can be used for the requirements.

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 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: