Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in Bash [duplicate]

I would like to introduce multithreading feature in my shell script.

I have a script which calls the function read_cfg() with different arguments. Each of these function calls are independent.

Would it be possible to instantiate these function calls (not scripts) parallelly. Please let me how can we achieve that.. ?

like image 257
Kiran Avatar asked Mar 11 '10 14:03

Kiran


People also ask

Is multithreading possible in Bash?

When you execute a Bash script, it will at maximum use a single CPU thread, unless you start subshells/threads. If your machine has at least two CPU threads, you will be able to max-out CPU resources using multi-threaded scripting in Bash.

What is $2 in Bash?

$2 is the second command-line argument passed to the shell script or function. Also, know as Positional parameters.

What is $@ in Bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

Sure, just add & after the command:

read_cfg cfgA & read_cfg cfgB & read_cfg cfgC & wait 

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

like image 155
Martin Avatar answered Sep 24 '22 13:09

Martin