{"id":11383,"date":"2020-12-20T17:39:45","date_gmt":"2020-12-20T17:39:45","guid":{"rendered":"https:\/\/www.askpython.com\/?p=11383"},"modified":"2020-12-25T15:50:27","modified_gmt":"2020-12-25T15:50:27","slug":"multiprocessing-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/multiprocessing-in-python","title":{"rendered":"Multiprocessing In Python"},"content":{"rendered":"\n<p>Hey guys! In this article, we will learn about multiprocessing in Python. So, let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is multiprocessing?<\/h2>\n\n\n\n<p>Multiprocessing is a package in python that supports the ability to spawn processes that make use of a Python API. It similar to the threading module in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding Multiprocessing in Python<\/h2>\n\n\n\n<p>A multiprocessor is a computer means that the computer has more than one central processor. If a computer has only one processor with multiple cores, the tasks can be run parallel using <a href=\"https:\/\/www.askpython.com\/python-modules\/multithreading-in-python\" class=\"rank-math-link\">multithreading in Python<\/a>. <\/p>\n\n\n\n<p>A multiprocessor system has the ability to support more than one processor at the same time. To find the number of CPU cores available on our system, we use <em><strong>mp.cpu_count()<\/strong> <\/em>function.<\/p>\n\n\n\n<p>In this article, we&#8217;ll be using Python&#8217;s multiprocessing module<\/p>\n\n\n\n<p><strong>Here&#8217;s a sample code to find processor count in Python using the multiprocessing module:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport multiprocessing as mp\n\nprint(mp.cpu_count())\n<\/pre><\/div>\n\n\n<p>Output: <strong>12<\/strong><\/p>\n\n\n\n<p>The count here is the total number of cores between multiple processors, summed up. <\/p>\n\n\n\n<p><strong>The four most important classes of this module are- <\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Process Class<\/li><li>Lock Class<\/li><li>Queue Class<\/li><li>Pool Class <\/li><\/ul>\n\n\n\n<p>Let&#8217;s look at each of these classes individually&#8230; <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Process Class<\/h3>\n\n\n\n<p>Process is the forked copy of the current process. It creates a new process identifier and tasks run as independent child process. <\/p>\n\n\n\n<p><strong><em>start()<\/em><\/strong> and <em><strong>join()<\/strong><\/em> functions belong to this class. To pass an argument through a process, we use <strong><em>args<\/em><\/strong> keyword.<\/p>\n\n\n\n<p>Example of start() function-<\/p>\n\n\n\n<p>Here, we have created a function <em>calc_square<\/em> and <em>calc_cube<\/em> for finding square and cube of the number respectively. In the main function we have created the objects <em>p1<\/em> and <em>p2<\/em>. <em>p1.start()<\/em> and <em>p2.start()<\/em> will start the function and calling <em>p1.join() and p2.join<\/em> will terminate the process.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport time\nimport multiprocessing\n\ndef calc_square(numbers):\n\tfor n in numbers:\n\t\tprint(&#039;square &#039; + str(n*n))\n\ndef calc_cube(numbers):\n\tfor n in numbers:\n\t\tprint(&#039;cube &#039;+ str(n*n*n))\n\nif __name__ == &quot;__main__&quot;:\n\tarr=&#x5B;2,3,8,9]\n\tp1=multiprocessing.Process(target=calc_square,args=(arr,))\n\tp2=multiprocessing.Process(target=calc_cube,args=(arr,))\n\n\tp1.start()\n\tp2.start()\n\n\tp1.join()\n\tp2.join()\n\n\tprint(&quot;Done&quot;)\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nsquare 4\nsquare 9\nsquare 64\nsquare 81\ncube 8\ncube 27\ncube 512\ncube 729\nDone\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Lock Class<\/h3>\n\n\n\n<p>The lock class allows the code to be locked in order to make sure that no other process can execute the similar code until it is released. <\/p>\n\n\n\n<p>To claim the lock, <em><strong>acquire() <\/strong><\/em>function is used and to release the lock, <strong><em>release()<\/em><\/strong> function is used.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom multiprocessing import Process, Lock\n\nlock=Lock()\ndef printer(data):\n  lock.acquire()\n  try:\n      print(data)\n  finally:\n      lock.release()\n\nif __name__==&quot;__main__&quot;:\n  items=&#x5B;&#039;mobile&#039;,&#039;computer&#039;,&#039;tablet&#039;]\n  for item in items:\n     p=Process(target=printer,args=(item,))\n     p.start()\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nmobile\ncomputer\ntablet\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. Queue Class<\/h3>\n\n\n\n<p>Queue is a data structure which uses First In First Out (FIFO) technique.It helps us perform inter process communication using native Python objects. <\/p>\n\n\n\n<p>Queue enables the Process to consume shared data when passed as a parameter.<\/p>\n\n\n\n<p><em><strong>put()<\/strong><\/em> function is used to insert data to the queue and <strong><em>get()<\/em><\/strong> function is used to consume data from the queue. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport multiprocessing as mp\n\ndef sqr(x,q):\n\tq.put(x*x)\n\nif __name__ == &quot;__main__&quot;:\n\tq=mp.Queue() # Instance of queue class created\n\tprocesses=&#x5B;mp.Process(target=sqr,args=(i,q))for i in range (2,10)] # List of processes within range 2 to 10\n\tfor p in processes:\n\t\tp.start()\n\n\tfor p in processes:\n\t\tp.join()\n\n\tresult = &#x5B;q.get() for p in processes]\n\tprint(result)\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;4, 9, 16, 25, 36, 64, 49, 81]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">4. Pool Class<\/h3>\n\n\n\n<p>The pool class helps us execute a function against multiple input values in parallel. This concept is called Data Parallelism.<\/p>\n\n\n\n<p>Here, array [5,9,8] is mapped as input in the function call. pool.map() function is used to pass a list of multiple arguments.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport multiprocessing as mp\n\ndef my_func(x):\n  print(x**x)\n\ndef main():\n  pool = mp.Pool(mp.cpu_count())\n  result = pool.map(my_func, &#x5B;5,9,8])\n\nif __name__ == &quot;__main__&quot;:\n  main()\n<\/pre><\/div>\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n3125\n387420489\n16777216\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned the four most important classes in multiprocessing in Python &#8211; Process, Lock, Queue, and Pool which enables better utilization of CPU cores and improves performance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p><a href=\"https:\/\/docs.python.org\/3\/library\/multiprocessing.html\" target=\"_blank\" aria-label=\" (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"rank-math-link\">Official Module documentation<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey guys! In this article, we will learn about multiprocessing in Python. So, let&#8217;s get started. What is multiprocessing? Multiprocessing is a package in python that supports the ability to spawn processes that make use of a Python API. It similar to the threading module in Python. Understanding Multiprocessing in Python A multiprocessor is a [&hellip;]<\/p>\n","protected":false},"author":18,"featured_media":11496,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-11383","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11383","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/18"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=11383"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/11383\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/11496"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=11383"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=11383"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=11383"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}