Run Command on Multiple Threads in Bash

bashcentosmultithreading

I am running a command (pngquant to be precise: https://github.com/pornel/pngquant) in a terminal window. I noticed, that if I open 4 terminal windows, and run pngquant command in each of them, I get 4x speed increase, effectively compressing 4 times as many images in the same time as before.

So I used this approach and assigned each pngqunat process a portion of images I want to compress, effectively creating multiple processes on multiple threads

Can you run command on multiple threads without doing this tricks that I did? I would like to just say "run pngquant compression on all this images and use all threads available."

Best Answer

Both moreutils parallel and GNU parallel will do this for you. With moreutils' parallel, it looks like:

parallel -j "$(nproc)" pngquant [pngquant-options] -- *.png

nproc outputs the number of available processors (threads), so that will run available-processors (-j "$(nproc)") pngquants at once, passing each a single PNG file. If the startup overhead is too high, you can pass more PNG files at once to each run with the -n option; -n 2 would pass two PNGs to each pngquant.

Related Question