<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by KAVISHA MEHTA on Medium]]></title>
        <description><![CDATA[Stories by KAVISHA MEHTA on Medium]]></description>
        <link>https://medium.com/@mehta.kavisha?source=rss-10b335e22b00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QuBh4G3Xo6Wq7s2I8um-xA.jpeg</url>
            <title>Stories by KAVISHA MEHTA on Medium</title>
            <link>https://medium.com/@mehta.kavisha?source=rss-10b335e22b00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:23:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehta.kavisha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Different Methods of Multiprocessing in Python]]></title>
            <link>https://medium.com/@mehta.kavisha/different-methods-of-multiprocessing-in-python-70eb4009a990?source=rss-10b335e22b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/70eb4009a990</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-parallelism]]></category>
            <category><![CDATA[multiprocessing]]></category>
            <dc:creator><![CDATA[KAVISHA MEHTA]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 13:11:04 GMT</pubDate>
            <atom:updated>2022-12-10T13:11:04.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Having a problem statement performing a number of computations simultaneously on the same input with each computation yielding a different independent result each time. This task can be achieved using a number of methods, but which method is the most efficient? Let’s study each method and compare it with others to achieve the goal.</p><figure><img alt="Parallelism overview" src="https://cdn-images-1.medium.com/max/1024/1*f-1o0JNdXT7vUaB0Kb1sEQ.jpeg" /></figure><h3>Process Based Parallelism</h3><h4>What is Parallelism?</h4><p>The solution to the above-defined problem can be achieved using process-based parallelism. But what is parallelism? <strong>Parallelism</strong> means two or more computations happening at the same unit of time. Parallelism can also be said as a specific use-case of concurrency.</p><p><strong>Process Based Parallelism</strong> in Python can be achieved by creating multiple processes, with each process having its own Processing unit ( For eg . Instead of one task being performed by one processor, multiprocessors perform independent parts of the task simultaneously.</p><h4>Multiprocessing in Python</h4><p>One way to achieve process-based parallelism in python is by using the <em>multiprocessing </em>module. The <em>multiprocessing</em> module allows you to create multiple processes with each of them having its own python interpreter.</p><p>Python’s multiprocessing library offers two ways to implement Process-based parallelism</p><ul><li>Using the Process Class</li><li>Using the Pool Class</li></ul><h4>The Process Class</h4><p>When you have a set of heterogeneous tasks to be executed in parallel, the process is used. It is used for function-based parallelism with each function performing a specific task. Each process needs to be created explicitly and hence makes it user-managed/program-managed.</p><h4>The Pool Class</h4><p>A process pool is a programming pattern for automatically managing a pool of worker processes. . The Pool Class automatically distributes the tasks to the available processors using a FIFO scheduling manner. when you have a set of homogeneous tasks to be executed in parallel, the Pool class is used. It is used for data-based parallelism with the same function being executed on multiple input values with each input value being assigned to a process.</p><p>The Pool class works like a map-reduce architecture. It maps different processors to different inputs and collects the output from all the processors and gives a combined result</p><h4>Process Class Vs Pool Class</h4><figure><img alt="Process Vs Pool difference" src="https://cdn-images-1.medium.com/max/1024/1*cbGpT9QLY1H6_iJHwU8xOA.png" /></figure><figure><img alt="Difference between process and pool class" src="https://cdn-images-1.medium.com/max/883/1*ZJjDco35KZUeRfQlMMCWaQ.png" /></figure><h4>An example</h4><ul><li><strong>The Process Class</strong></li></ul><pre>#The Process Class<br>from multiprocessing import Process<br><br>def function1(data d):<br>    x = task1(d)<br>    y = task2(d)<br>    return (x*y)<br><br>def function2():<br>    x = task1(d)<br>    y = task2(d)<br>    return (x+y)<br><br>data = [d1,d2,d2]<br><br>for d in data:<br>  p1 = Process(target=function1, args=(d))<br>  p2 = Process(target=function2, args=(d))<br>  <br>  p1.start()<br>  p2.start()<br>  p1.join()<br>  p2.join()</pre><ul><li><strong>The Pool Class</strong></li></ul><pre>#The Pool Class<br>from multiprocessing import Pool<br><br>def function1(data d):<br>    x = task1(d)<br>    y = task2(d)<br>    return (x*y)<br><br>data = [d1,d2,d2]<br><br>pool = Pool(processes=2) <br>      <br>p1 = pool.map_async(function1,data)<br><br>p1.start()<br>p1.join()</pre><p>The first scenario starts two separate processes (call them P1 and P2) and starts P1 running <em>function1 </em>on data<em> d1 </em>and P2 running <em>function2 </em>on data<em> d1</em>, and thereby on the remaining data <em>(d2 and d3)</em> then waits until both processes have finished their respective tasks.</p><p>The second scenario starts with two processes (call them Q1 and Q2) and starts Q1 running <em>function1</em> on <em>data1 </em>and Q2 running <em>function1</em> on <em>data2</em> thereby either on Q1 or Q3 on the remaining data <em>d3</em>.</p><h3>Methods to achieve Data-based Parallelism using multiprocessing.Pool</h3><p>In order to understand the different ways to achieve multiprocessing using the Pool class, Let’s first understand the lifecycle any pool Process goes through in its lifetime.</p><h4>Life Cycle of a pool Process</h4><figure><img alt="Lifecycle of a Pool Process" src="https://cdn-images-1.medium.com/max/625/1*WYz7cKvrgkng8Mav2cbBDA.jpeg" /></figure><p>In this article, let’s have a closer look at the 1st 2 steps of the life cycle.</p><h4>Step -1: Create a Pool Instance</h4><p>An instance of <em>multiprocessing.Pool </em>class needs to be created to create a multiprocess pool. The instance can be configured by specifying arguments to the Pool constructor.</p><ul><li><strong>Syntax to create a pool instance</strong></li></ul><pre>class multiprocessing.Pool(<br>                 [processes[, <br>                 initializer[,<br>                 initargs[,<br>                 maxtasksperchild]]]]<br>                 )</pre><p>Following are the arguments that can be configured</p><ol><li><strong>processes </strong>[optional]:- Specifies the maximum number of processes to be initialized by the pool. If specified as <em>None</em> the default value used is the value returned by the <em>cpu_count</em><strong><em>() </em></strong>function.</li><li><strong>initializer </strong>[optional]:- Specifies the function each process executes post creation. If the initializer is not <em>None </em>then each worker process calls the function specified initializer(*initargs).</li><li><strong>initargs </strong>[optional]<strong>:- </strong>Specifies the arguments supplied to the initializer function.</li><li><strong>maxtasksperchild </strong>[optional]<strong>:- </strong>Specifies<strong> </strong>the number of tasks executed by a worker process before exiting and replacing itself with a fresh worker process. If the maxtasksperchild is specified as <em>None , </em>in that case the worker process will live as long as the pool.</li></ol><p><em>Note :- maxtasksperchild was introduced in v3.2 with the primary goal to free up unused resources.</em></p><h4>Step -2: Submit a pool Process</h4><p>Once a pool instance is initialized, tasks can be submitted to the pool. Tasks can be submitted to the pool worker using 2 approaches</p><ol><li>Issue tasks Synchronously :</li><li>Issue tasks Asynchronously</li></ol><h4>Step -2(1) — Issue tasks Synchronously</h4><p>When tasks are issued synchronously, the caller is blocked until all the tasks are executed/terminated.</p><p>Following are the methods to issue tasks synchronously</p><ol><li>map</li><li>apply</li><li>starmap</li></ol><h4>The Map Function</h4><p>Syntax of the function</p><pre>map(func, iterable[, chunksize])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>iterable</strong>: Specifies the data/iterable which is supplied as an input. The iterable is divided and executed based on the pool size specified.</li><li><strong>chunksize</strong>: [optional]:- Specifies the number of iterables given to each pool process.</li></ol><p>The multiprocessing <strong>map</strong> function is similar to python map functions. It blocks the main process until the subprocess completes. The map function supports only one argument (should be iterable) to be supplied to it. It does not support the functionality of callback functions. Results are ordered.</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def mul(x):<br>    print(f&quot;start process {x}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x}&quot;)<br>    res = x[0] * x[1]<br>    res_ap = (x[0] , x[1] , res)<br>    return res_ap<br><br># Map<br>def test_map():<br>    pool = Pool(processes=10)<br>    res = pool.map(mul, lst,chunksize=2)<br>    result.append(res)<br>    pool.close()<br>    pool.join()<br>    print(result)<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_map()<br>    print(&quot;End Time Map:&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><ul><li>with a chunksize=2</li></ul><figure><img alt="chunksize=2 output" src="https://cdn-images-1.medium.com/max/1024/1*tkObo2QZjJI5dz6ZNqzKyQ.png" /></figure><ul><li>with a chunksize=1</li></ul><figure><img alt="chunksize=1 output" src="https://cdn-images-1.medium.com/max/986/1*QySjzgrgdTJacA4Llz7uVA.png" /></figure><h4>The Apply Function</h4><p>Syntax of the function</p><pre>apply(func[, args[, kwds]])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>args</strong>: Specifies the arguments/data which is supplied as an input to the function.</li><li><strong>kwds</strong>: [optional]:- Specifies the keyword arguments supplied to the function</li></ol><p>The multiprocess <strong>apply</strong> function processes only one iterable at a time. It blocks the caller till the 1st iterable completes. Results are unordered in case of apply.</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def mulX(x, y):<br>    print(f&quot;start process {x} - {y}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x} - {y}&quot;)<br>    res = x * y<br>    res_ap = (x, y, res)<br>    return res_ap<br><br># Apply<br>def test_apply():<br>    pool = Pool(processes=10)<br>    for x,y in lst:<br>        res = pool.apply(mulX, args=(x,y))<br>        result.append(res)<br>    pool.close()<br>    pool.join()<br>    print(result)<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_apply()<br>    print(&quot;End Time Apply:&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><figure><img alt="output apply function" src="https://cdn-images-1.medium.com/max/1024/1*fQc-64pUBmBcderHFZX72g.png" /></figure><h4>The Starmap Function</h4><p>Syntax of the function</p><pre>starmap(func, iterable[, chunksize])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>iterable</strong>: Specifies the data/iterable which is supplied as an input. The iterable is divided and executed based on the pool size specified.</li><li><strong>chunksize</strong>: [optional]:- Specifies the number of iterables given to each pool process.</li></ol><p>The multiprocessing <strong>starmap </strong>function is similar to the map function. It supports multiple arguments as input.</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def mulX(x, y):<br>    print(f&quot;start process {x} - {y}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x} - {y}&quot;)<br>    res = x * y<br>    res_ap = (x, y, res)<br>    return res_ap<br><br># Starmap<br>def test_starmap():<br><br>    pool = Pool(processes=10)<br>    res = pool.starmap(mulX, lst,chunksize=2)<br>    result.append(res)<br>    pool.close()<br>    pool.join()<br>    print(result)<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_starmap()<br>    print(&quot;End Time Starmap :&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*E8W_PTdve0E_wv2fXldioA.png" /></figure><h4>Step -2(2) — Issue tasks Asynchronously</h4><p>When tasks are issued synchronously, the caller is not blocked until all the tasks are executed/terminated. (i.e allowing the caller to continue on with other work while the tasks are executed.). The caller in such cases returns immediately and provides a hook or mechanism to get the results after the execution of all tasks is completed.</p><ol><li>map_async</li><li>apply_async</li><li>starmap_async</li></ol><h4>The map_async function</h4><p>Syntax of the function</p><pre>map_async(func, iterable[, chunksize[, callback[, error_callback]]])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>iterable</strong>: Specifies the data/iterable which is supplied as an input. The iterable is divided and executed based on the pool size specified.</li><li><strong>chunksize</strong>: [optional]:- Specifies the number of iterables given to each pool process.</li><li><strong>callback: </strong>[optional]:- A callable function that is executed post the results of the multiprocessing are ready, in case of successful execution of the function. It accepts a single argument.</li><li><strong>error_callback: </strong>[optional]:-A callable function that is executed in case of unsuccessful execution of the function. It accepts a single argument which is the exception instance.</li></ol><p>The multiprocessing <strong>map_async</strong> function is a variant of the map() method that returns an async result. It supports the callback functionality. The Callbacks specified should complete their execution immediately since otherwise the thread which handles the results gets blocked. <em>Result_variable.get(timeout)</em> is used to get the results, which fetches the result until the timeout occurs.</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def collect_result(val):<br>    # print(f&quot;writing result {val}&quot;)<br>    return result.append(val)<br><br>def mul(x):<br>    print(f&quot;start process {x}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x}&quot;)<br>    res = x[0] * x[1]<br>    res_ap = (x[0] , x[1] , res)<br>    return res_ap<br><br># Map Async<br>def test_map_async():<br>    pool = Pool(processes=10)<br>    result_f =  pool.map_async(mul, lst,chunksize=2 ,callback=collect_result)<br>    pool.close()<br>    print(result_f.get(timeout=10))<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_map_async()<br>    print(&quot;End Time Map Async:&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><figure><img alt="output map_async" src="https://cdn-images-1.medium.com/max/986/1*KHAabXYVIQ2EbiRlfzmsmw.png" /></figure><h4>The apply_async function</h4><p>Syntax of the function</p><pre>apply_async(func[, args[, kwds[, callback[, error_callback]]]])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>args</strong>: Specifies the arguments/data which is supplied as an input to the function.</li><li><strong>kwds</strong>: [optional]:- Specifies the keyword arguments supplied to the function</li><li><strong>callback: </strong>[optional]:- A callable function that is executed post the results of the multiprocessing are ready, in case of successful execution of the function. It accepts a single argument.</li><li><strong>error_callback: </strong>[optional]:-A callable function that is executed in case of unsuccessful execution of the function. It accepts a single argument which is the exception instance.</li></ol><p>The multiprocessing <strong>apply_async</strong> function is similar to apply() function , with the difference that it executes the job in an async manner in the background. It supports callback and error_callback functionality and returns an ApplyResult object</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def collect_result(val):<br>    # print(f&quot;writing result {val}&quot;)<br>    return result.append(val)<br><br>def mulX(x, y):<br>    print(f&quot;start process {x} - {y}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x} - {y}&quot;)<br>    res = x * y<br>    res_ap = (x, y, res)<br>    return res_ap<br><br># Apply Async<br>def test_apply_async():<br>    result_f = &#39;&#39;<br>    result_final=[]<br><br>    pool = Pool(processes=10)<br>    for x,y in lst:<br>         result_f = pool.apply_async(mulX, args=(x,y), callback=collect_result)<br>         result_final.append(result_f)<br><br>    pool.close()<br>    for f_res in result_final:<br>        r = f_res.get(timeout=10)<br>        print(r)<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_apply_async()<br>    print(&quot;End Time Apply Async:&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><figure><img alt="apply_async output" src="https://cdn-images-1.medium.com/max/1024/0*hxRTDdxNdknpSz0b" /></figure><h4>The starmap_async function</h4><p>Syntax of the function</p><pre>starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])</pre><ol><li><strong>func</strong>: Specifies the function to be executed</li><li><strong>iterable</strong>: Specifies the data/iterable which is supplied as an input. The iterable is divided and executed based on the pool size specified.</li><li><strong>chunksize</strong>: [optional]:- Specifies the number of iterables given to each pool process.</li><li><strong>callback: </strong>[optional]:- A callable function that is executed post the results of the multiprocessing are ready, in case of successful execution of the function. It accepts a single argument.</li><li><strong>error_callback: </strong>[optional]:-A callable function that is executed in case of unsuccessful execution of the function. It accepts a single argument which is the exception instance.</li></ol><p>The multiprocessing <strong>starmap_async </strong>function is a combination of <em>starmap() </em>and <em>map_async(). </em>It Iterates over iterable with values unpacked, i.e supports multiple arguments of an iterable similar to the map function.</p><p><strong>Example</strong></p><pre>from datetime import datetime<br>from multiprocessing import Pool<br>import time<br><br>lst = [(2, 2),  (4, 4), (5, 5),(6,6),(3, 3),]<br>result = []<br><br>def collect_result(val):<br>    # print(f&quot;writing result {val}&quot;)<br>    return result.append(val)<br><br>def mulX(x, y):<br>    print(f&quot;start process {x} - {y}&quot;)<br>    time.sleep(3)<br>    print(f&quot;end process {x} - {y}&quot;)<br>    res = x * y<br>    res_ap = (x, y, res)<br>    return res_ap<br><br># Starmap Async<br>def test_starmap_async():<br>    pool = Pool(processes=10)<br>    result_f = pool.starmap_async(mulX, lst,chunksize=3 ,callback=collect_result)<br><br>    pool.close()<br>    print(result_f.get())<br><br>if __name__ == &#39;__main__&#39;:<br>    start = datetime.now()<br>    test_starmap_async()<br>    print(&quot;End Time Starmap Async:&quot;, (datetime.now() - start).total_seconds())</pre><p><strong>Output</strong></p><figure><img alt="starmap_async output" src="https://cdn-images-1.medium.com/max/1024/0*Rmd7NX4gyacxVGhV" /></figure><h3>Summarizing the methods of submitting a task to the pool</h3><p>The below table summarizes the different methods to submit a task to a multiprocessing pool. It also depicts the key characteristics of all the functions</p><figure><img alt="comparison table" src="https://cdn-images-1.medium.com/max/1024/1*A_rvsw7es2mcpUJbkEgglw.png" /></figure><h4>Key Points to Remember</h4><ul><li>Pool.imap and Pool.imap_async are the lazier version of map and map_async.</li><li>pool. close() method prevents further execution of tasks within the pool. This function is called when all the tasks have been completed and the worker processes exits.</li><li>pool. join() waits for the worker processes to exit. One must call close() or terminate() before using join()</li><li>Pool Function requires that the __main__ module to be importable by the children. This means multiprocessing.Pool will not work in the interactive interpreter.</li><li>The billiard library is a fork of the Python 2.7 multiprocessing package.</li></ul><h3>Conclusion</h3><p>The article gives an overview of process-based parallelism using multiprocessing in python. We went through the 2 methods to achieve the same and the key differences between the Process and the Pool function.</p><p>Further, we drilled down to a detailed view of achieving data-based parallelism using the multiprocessing pool function and the different methods used to submit a task to the pool. The article also covers the key differences between the methods.</p><h3>References:-</h3><ul><li><a href="https://superfastpython.com/multiprocessing-pool-python/">https://superfastpython.com/multiprocessing-pool-python/</a></li><li><a href="https://billiard.readthedocs.io/en/latest/library/multiprocessing.html#module-multiprocessing">https://billiard.readthedocs.io/en/latest/library/multiprocessing.html#module-multiprocessing</a></li><li><a href="https://ellicium.com/blog/python-multiprocessing-pool-process/">https://ellicium.com/blog/python-multiprocessing-pool-process/</a></li><li><a href="https://lih-verma.medium.com/multi-processing-in-python-process-vs-pool-5caf0f67eb2b">https://lih-verma.medium.com/multi-processing-in-python-process-vs-pool-5caf0f67eb2b</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70eb4009a990" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>