You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

542 lines
18 KiB

4 years ago
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Supercharge Your Bash Scripts with Multiprocessing :: Fr1nge&#39;s Personal Blog</title>
  5. <meta http-equiv="content-type" content="text/html; charset=utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta name="description" content="Bash is a great tool for automating tasks and improving you work flow. However, it is ***SLOW***. Adding multiprocessing to the scripts you write can improve the performance greatly." />
  8. <meta name="keywords" content="bash, scripting" />
  9. <meta name="robots" content="noodp" />
  10. <link rel="canonical" href="http://fr1nge.xyz/posts/supercharge-your-bash-scripts-with-multiprocessing/" />
  11. <link rel="stylesheet" href="http://fr1nge.xyz/assets/style.css">
  12. <link rel="stylesheet" href="http://fr1nge.xyz/assets/blue.css">
  13. <link rel="apple-touch-icon" href="http://fr1nge.xyz/img/apple-touch-icon-192x192.png">
  14. <link rel="shortcut icon" href="http://fr1nge.xyz/img/favicon/blue.png">
  15. <meta name="twitter:card" content="summary" />
  16. <meta name="twitter:site" content="yigitcolakoglu.com" />
  17. <meta name="twitter:creator" content="theFr1nge" />
  18. <meta property="og:locale" content="en" />
  19. <meta property="og:type" content="article" />
  20. <meta property="og:title" content="Supercharge Your Bash Scripts with Multiprocessing">
  21. <meta property="og:description" content="Bash is a great tool for automating tasks and improving you work flow. However, it is ***SLOW***. Adding multiprocessing to the scripts you write can improve the performance greatly." />
  22. <meta property="og:url" content="http://fr1nge.xyz/posts/supercharge-your-bash-scripts-with-multiprocessing/" />
  23. <meta property="og:site_name" content="Fr1nge&#39;s Personal Blog" />
  24. <meta property="og:image" content="http://fr1nge.xyz/">
  25. <meta property="og:image:width" content="2048">
  26. <meta property="og:image:height" content="1024">
  27. <meta property="article:published_time" content="2021-05-05 17:08:12 &#43;0300 &#43;03" />
  28. </head>
  29. <body class="blue">
  30. <div class="container center headings--one-size">
  31. <header class="header">
  32. <div class="header__inner">
  33. <div class="header__logo">
  34. <a href="/">
  35. <div class="logo">
  36. fr1nge.xyz
  37. </div>
  38. </a>
  39. </div>
  40. <div class="menu-trigger">menu</div>
  41. </div>
  42. <nav class="menu">
  43. <ul class="menu__inner menu__inner--desktop">
  44. <li><a href="/about">About</a></li>
  45. <li><a href="/awards">Awards &amp; Certificates</a></li>
  46. <li><a href="/projects">Projects</a></li>
  47. </ul>
  48. <ul class="menu__inner menu__inner--mobile">
  49. <li><a href="/about">About</a></li>
  50. <li><a href="/awards">Awards &amp; Certificates</a></li>
  51. <li><a href="/projects">Projects</a></li>
  52. </ul>
  53. </nav>
  54. </header>
  55. <div class="content">
  56. <div class="post">
  57. <h1 class="post-title">
  58. <a href="http://fr1nge.xyz/posts/supercharge-your-bash-scripts-with-multiprocessing/">Supercharge Your Bash Scripts with Multiprocessing</a></h1>
  59. <div class="post-meta">
  60. <span class="post-date">
  61. 2021-05-05 [Updated: 2021-05-05]
  62. </span>
  63. <span class="post-author">:: Yigit Colakoglu</span>
  64. </div>
  65. <span class="post-tags">
  66. #<a href="http://fr1nge.xyz/tags/bash/">bash</a>&nbsp;
  67. #<a href="http://fr1nge.xyz/tags/scripting/">scripting</a>&nbsp;
  68. #<a href="http://fr1nge.xyz/tags/programming/">programming</a>&nbsp;
  69. </span>
  70. <div class="post-content"><div>
  71. <p>Bash is a great tool for automating tasks and improving you work flow. However,
  72. it is <em><strong>SLOW</strong></em>. Adding multiprocessing to the scripts you write can improve
  73. the performance greatly.</p>
  74. <h2 id="what-is-multiprocessing">What is multiprocessing?<a href="#what-is-multiprocessing" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h2>
  75. <p>In the simplest terms, multiprocessing is the principle of splitting the
  76. computations or jobs that a script has to do and running them on different
  77. processes. In even simpler terms however, multiprocessing is the computer
  78. science equivalent of hiring more than one
  79. worker when you are constructing a building.</p>
  80. <h3 id="introducing-">Introducing &ldquo;&amp;&rdquo;<a href="#introducing-" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h3>
  81. <p>While implementing multiprocessing the sign <code>&amp;</code> is going to be our greatest
  82. friend. It is an essential sign if you are writing bash scripts and a very
  83. useful tool in general when you are in the terminal. What <code>&amp;</code> does is that it
  84. makes the command you added it to the end of run in the background and allows
  85. the rest of the script to continue running as the command runs in the
  86. background. One thing to keep in mind is that since it creates a fork of the
  87. process you ran the command on, if you change a variable that the command in the
  88. background uses while it runs, it will not be affected. Here is a simple
  89. example:</p>
  90. <div class="collapsable-code">
  91. <input id="1" type="checkbox" />
  92. <label for="1">
  93. <span class="collapsable-code__language">bash</span>
  94. <span class="collapsable-code__toggle" data-label-expand="Show" data-label-collapse="Hide"></span>
  95. </label>
  96. <pre class="language-bash" ><code>
  97. foo=&#34;yeet&#34;
  98. function run_in_background(){
  99. sleep 0.5
  100. echo &#34;The value of foo in the function run_in_background is $foo&#34;
  101. }
  102. run_in_background &amp; # Spawn the function run_in_background in the background
  103. foo=&#34;YEET&#34;
  104. echo &#34;The value of foo changed to $foo.&#34;
  105. wait # wait for the background process to finish
  106. </code></pre>
  107. </div>
  108. <p>This should output:</p>
  109. <pre><code>The value of foo changed to YEET.
  110. The value of foo in here is yeet
  111. </code></pre><p>As you can see, the value of <code>foo</code> did not change in the background process even though
  112. we changed it in the main function.</p>
  113. <h2 id="baby-steps">Baby steps&hellip;<a href="#baby-steps" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h2>
  114. <p>Just like anything related to computer science, there is more than one way of
  115. achieving our goal. We are going to take the easier, less intimidating but less
  116. efficient route first before moving on to the big boy implementation. Let&rsquo;s open up vim and get to scripting!
  117. First of all, let&rsquo;s write a very simple function that allows us to easily test
  118. our implementation:</p>
  119. <div class="collapsable-code">
  120. <input id="1" type="checkbox" />
  121. <label for="1">
  122. <span class="collapsable-code__language">bash</span>
  123. <span class="collapsable-code__toggle" data-label-expand="Show" data-label-collapse="Hide"></span>
  124. </label>
  125. <pre class="language-bash" ><code>
  126. function tester(){
  127. # A function that takes an int as a parameter and sleeps
  128. echo &#34;$1&#34;
  129. sleep &#34;$1&#34;
  130. echo &#34;ENDED $1&#34;
  131. }
  132. </code></pre>
  133. </div>
  134. <p>Now that we have something to run in our processes, we now need to spawn several
  135. of them in controlled manner. Controlled being the keyword here. That&rsquo;s because
  136. each system has a maximum number of processes that can be spawned (You can find
  137. that out with the command <code>ulimit -u</code>). In our case, we want to limit the
  138. processes being ran to the variable <code>num_processes</code>. Here is the implementation:</p>
  139. <div class="collapsable-code">
  140. <input id="1" type="checkbox" />
  141. <label for="1">
  142. <span class="collapsable-code__language">bash</span>
  143. <span class="collapsable-code__toggle" data-label-expand="Show" data-label-collapse="Hide"></span>
  144. </label>
  145. <pre class="language-bash" ><code>
  146. num_processes=$1
  147. pcount=0
  148. for i in {1..10}; do
  149. ((pcount=pcount%num_processes));
  150. ((pcount&#43;&#43;==0)) &amp;&amp; wait
  151. tester $i &amp;
  152. done
  153. </code></pre>
  154. </div>
  155. <p>What this loop does is that it takes the number of processes you would like to
  156. spawn as an argument and runs <code>tester</code> in that many processes. Go ahead and test it out!
  157. You might notice however that the processes are run int batches. And the size of
  158. batches is the <code>num_processes</code> variable. The reason this happens is because
  159. every time we spawn <code>num_processes</code> processes, we <code>wait</code> for all the processes
  160. to end. This implementation is not a problem in itself, there are many cases
  161. where you can use this implementation and it works perfectly fine. However, if
  162. you don&rsquo;t want this to happen, we have to dump this naive approach all together
  163. and improve our tool belt.</p>
  164. <h2 id="real-chads-use-job-pools">Real Chads use Job Pools<a href="#real-chads-use-job-pools" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h2>
  165. <p>The solution to the bottleneck that was introduced in our previous approach lies
  166. in using job pools. Job pools are where jobs created by a main process get sent
  167. and wait to get executed. This approach solves our problems because instead of
  168. spawning a new process for every copy and waiting for all the processes to
  169. finish we instead only create a set number of processes(workers) which
  170. continuously pick up jobs from the job pool not waiting for any other process to finish.
  171. Here is the implementation that uses job pools. Brace yourselves, because it is
  172. kind of complicated.</p>
  173. <div class="collapsable-code">
  174. <input id="1" type="checkbox" />
  175. <label for="1">
  176. <span class="collapsable-code__language">bash</span>
  177. <span class="collapsable-code__toggle" data-label-expand="Show" data-label-collapse="Hide"></span>
  178. </label>
  179. <pre class="language-bash" ><code>
  180. job_pool_end_of_jobs=&#34;NO_JOB_LEFT&#34;
  181. job_pool_job_queue=/tmp/job_pool_job_queue_$$
  182. job_pool_progress=/tmp/job_pool_progress_$$
  183. job_pool_pool_size=-1
  184. job_pool_nerrors=0
  185. function job_pool_cleanup()
  186. {
  187. rm -f ${job_pool_job_queue}
  188. rm -f ${job_pool_progress}
  189. }
  190. function job_pool_exit_handler()
  191. {
  192. job_pool_stop_workers
  193. job_pool_cleanup
  194. }
  195. function job_pool_worker()
  196. {
  197. local id=$1
  198. local job_queue=$2
  199. local cmd=
  200. local args=
  201. exec 7&lt;&gt; ${job_queue}
  202. while [[ &#34;${cmd}&#34; != &#34;${job_pool_end_of_jobs}&#34; &amp;&amp; -e &#34;${job_queue}&#34; ]]; do
  203. flock --exclusive 7
  204. IFS=$&#39;\v&#39;
  205. read cmd args &lt;${job_queue}
  206. set -- ${args}
  207. unset IFS
  208. flock --unlock 7
  209. if [[ &#34;${cmd}&#34; == &#34;${job_pool_end_of_jobs}&#34; ]]; then
  210. echo &#34;${cmd}&#34; &gt;&amp;7
  211. else
  212. { ${cmd} &#34;$@&#34; ; }
  213. fi
  214. done
  215. exec 7&gt;&amp;-
  216. }
  217. function job_pool_stop_workers()
  218. {
  219. echo ${job_pool_end_of_jobs} &gt;&gt; ${job_pool_job_queue}
  220. wait
  221. }
  222. function job_pool_start_workers()
  223. {
  224. local job_queue=$1
  225. for ((i=0; i&lt;${job_pool_pool_size}; i&#43;&#43;)); do
  226. job_pool_worker ${i} ${job_queue} &amp;
  227. done
  228. }
  229. function job_pool_init()
  230. {
  231. local pool_size=$1
  232. job_pool_pool_size=${pool_size:=1}
  233. rm -rf ${job_pool_job_queue}
  234. rm -rf ${job_pool_progress}
  235. touch ${job_pool_progress}
  236. mkfifo ${job_pool_job_queue}
  237. echo 0 &gt;${job_pool_progress} &amp;
  238. job_pool_start_workers ${job_pool_job_queue}
  239. }
  240. function job_pool_shutdown()
  241. {
  242. job_pool_stop_workers
  243. job_pool_cleanup
  244. }
  245. function job_pool_run()
  246. {
  247. if [[ &#34;${job_pool_pool_size}&#34; == &#34;-1&#34; ]]; then
  248. job_pool_init
  249. fi
  250. printf &#34;%s\v&#34; &#34;$@&#34; &gt;&gt; ${job_pool_job_queue}
  251. echo &gt;&gt; ${job_pool_job_queue}
  252. }
  253. function job_pool_wait()
  254. {
  255. job_pool_stop_workers
  256. job_pool_start_workers ${job_pool_job_queue}
  257. }
  258. </code></pre>
  259. </div>
  260. <p>Ok&hellip; But that the actual fuck is going in here???</p>
  261. <h3 id="fifo-and-flock">fifo and flock<a href="#fifo-and-flock" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h3>
  262. <p>In order to understand what this code is doing, you first need to understand two
  263. key commands that we are using, <code>fifo</code> and <code>flock</code>. Despite their complicated
  264. names, they are actually quite simple. Let&rsquo;s check their man pages to figure out
  265. their purposes, shall we?</p>
  266. <h4 id="man-fifo">man fifo<a href="#man-fifo" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h4>
  267. <p>fifo&rsquo;s man page tells us that:</p>
  268. <pre><code>NAME
  269. fifo - first-in first-out special file, named pipe
  270. DESCRIPTION
  271. A FIFO special file (a named pipe) is similar to a pipe, except that
  272. it is accessed as part of the filesystem. It can be opened by multiple
  273. processes for reading or writing. When processes are exchanging data
  274. via the FIFO, the kernel passes all data internally without writing it
  275. to the filesystem. Thus, the FIFO special file has no contents on the
  276. filesystem; the filesystem entry merely serves as a reference point so
  277. that processes can access the pipe using a name in the filesystem.
  278. </code></pre><p>So put in <strong>very</strong> simple terms, a fifo is a named pipe that can allows
  279. communication between processes. Using a fifo allows us to loop through the jobs
  280. in the pool without having to delete them manually, because once we read them
  281. with <code>read cmd args &lt; ${job_queue}</code>, the job is out of the pipe and the next
  282. read outputs the next job in the pool. However the fact that we have multiple
  283. processes introduces one caveat, what if two processes access the pipe at the
  284. same time? They would run the same command and we don&rsquo;t want that. So we resort
  285. to using <code>flock</code>.</p>
  286. <h4 id="man-flock">man flock<a href="#man-flock" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h4>
  287. <p>flock&rsquo;s man page defines it as:</p>
  288. <pre><code> SYNOPSIS
  289. flock [options] file|directory command [arguments]
  290. flock [options] file|directory -c command
  291. flock [options] number
  292. DESCRIPTION
  293. This utility manages flock(2) locks from within shell scripts or from
  294. the command line.
  295. The first and second of the above forms wrap the lock around the
  296. execution of a command, in a manner similar to su(1) or newgrp(1).
  297. They lock a specified file or directory, which is created (assuming
  298. appropriate permissions) if it does not already exist. By default, if
  299. the lock cannot be immediately acquired, flock waits until the lock is
  300. available.
  301. The third form uses an open file by its file descriptor number. See
  302. the examples below for how that can be used.
  303. </code></pre><p>Cool, translated to modern English that us regular folks use, <code>flock</code> is a thin
  304. wrapper around the C standard function <code>flock</code> (see <code>man 2 flock</code> if you are
  305. interested). It is used to manage locks and has several forms. The one we are
  306. interested in is the third one. According to the man page, it uses and open file
  307. by its <strong>file descriptor number</strong>. Aha! so that was the purpose of the <code>exec 7&lt;&gt; ${job_queue}</code> calls in the <code>job_pool_worker</code> function. It would essentially
  308. assign the file descriptor 7 to the fifo <code>job_queue</code> and afterwards lock it with
  309. <code>flock --exclusive 7</code>. Cool. This way only one process at a time can read from
  310. the fifo <code>job_queue</code></p>
  311. <h2 id="great-but-how-do-i-use-this">Great! But how do I use this?<a href="#great-but-how-do-i-use-this" class="hanchor" ariaLabel="Anchor">&#8983;</a> </h2>
  312. <p>It depends on your preference, you can either save this in a file(e.g.
  313. job_pool.sh) and source it in your bash script. Or you can simply paste it
  314. inside an existing bash script. Whatever tickles your fancy. I have also
  315. provided an example that replicates our first implementation. Just paste the
  316. below code under our &ldquo;chad&rdquo; job pool script.</p>
  317. <div class="collapsable-code">
  318. <input id="1" type="checkbox" />
  319. <label for="1">
  320. <span class="collapsable-code__language">bash</span>
  321. <span class="collapsable-code__toggle" data-label-expand="Show" data-label-collapse="Hide"></span>
  322. </label>
  323. <pre class="language-bash" ><code>
  324. function tester(){
  325. # A function that takes an int as a parameter and sleeps
  326. echo &#34;$1&#34;
  327. sleep &#34;$1&#34;
  328. echo &#34;ENDED $1&#34;
  329. }
  330. num_workers=$1
  331. job_pool_init $num_workers
  332. pcount=0
  333. for i in {1..10}; do
  334. job_pool_run tester &#34;$i&#34;
  335. done
  336. job_pool_wait
  337. job_pool_shutdown
  338. </code></pre>
  339. </div>
  340. <p>Hopefully this article was(or will be) helpful to you. From now on, you don&rsquo;t
  341. ever have to write single threaded bash scripts like normies :)</p>
  342. </div></div>
  343. <div id="disqus_thread"></div>
  344. <script type="application/javascript">
  345. var disqus_config = function () {
  346. };
  347. (function() {
  348. if (["localhost", "127.0.0.1"].indexOf(window.location.hostname) != -1) {
  349. document.getElementById('disqus_thread').innerHTML = 'Disqus comments not available by default when the website is previewed locally.';
  350. return;
  351. }
  352. var d = document, s = d.createElement('script'); s.async = true;
  353. s.src = '//' + "fr1nge-xyz" + '.disqus.com/embed.js';
  354. s.setAttribute('data-timestamp', +new Date());
  355. (d.head || d.body).appendChild(s);
  356. })();
  357. </script>
  358. <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
  359. <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
  360. </div>
  361. </div>
  362. <footer class="footer">
  363. <div class="footer__inner">
  364. <div class="copyright copyright--user">
  365. <span>Yigit Colakoglu</span>
  366. <span>:: Theme made by <a href="https://twitter.com/panr">panr</a></span>
  367. </div>
  368. </div>
  369. </footer>
  370. <script src="http://fr1nge.xyz/assets/main.js"></script>
  371. <script src="http://fr1nge.xyz/assets/prism.js"></script>
  372. </div>
  373. </body>
  374. </html>