Step-by-Step Execution
Importing Pool
The Pool class is imported from multiprocessing. It is used to create multiple worker processes.
Defining the worker Function
The function worker(_) takes a single argument (which is unused, hence the underscore _).
When called, it prints "Hi".
Creating a Pool of Processes (with Pool(4) as p)
Pool(4) creates a pool of 4 worker processes.
The with statement ensures the pool is properly closed and cleaned up after use.
Using p.map(worker, range(6))
The map() function applies worker to each element in range(6), meaning it runs the function 6 times (worker(0), worker(1), ..., worker(5)).
Since the pool has 4 processes, the function runs in parallel, processing up to 4 tasks at a time.
Once a process completes its task, it picks the next available one.
Final Output:
6
0 Comments:
Post a Comment