import gevent from gevent.pool import Pool def task(n): print("Executing task %d" % n) gevent.sleep(1) print("Task %d complete" % n) pool = Pool(2) # create a pool with two greenlets tasks = [1, 2, 3, 4, 5] # create a list of tasks to execute # map the list of tasks to the pool results = pool.map_async(task, tasks) # wait for all tasks to complete results.wait()
import gevent from gevent.pool import Pool def task(n): print("Executing task %d" % n) gevent.sleep(1) print("Task %d complete" % n) return n def callback(result): print("Task %d returned %d" % (result, result)) pool = Pool(2) # create a pool with two greenlets tasks = [1, 2, 3, 4, 5] # create a list of tasks to execute # map the list of tasks to the pool results = pool.map_async(task, tasks) # call the callback function for each task when it completes for i, result in enumerate(results): callback(result.get())This example is similar to the previous one, but uses a `callback` function to handle the result of each task. The `map_async` method returns a `Greenlet` object for each task, which can be used to retrieve the result with the `get` method. The result is then passed to the `callback` function, which prints the task number and result. In conclusion, gevent.pool Pool is a part of the gevent library that allows you to execute tasks in parallel using greenlets. It provides a simple and efficient way to perform asynchronous programming in Python.