Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads in bash?

Is it possible to use threads in bash scripts. I have a driver class in java that i'm trying to run multiple instances of at the same time. The only way i know to do this is make threads in bash, but i'm not sure if thats even possible. Any help would be appreciated

like image 858
auwall Avatar asked May 27 '11 18:05

auwall


People also ask

Is bash multithreaded?

Parallel executes Bash scripts in parallel via a concept called multi-threading. This utility allows you to run different jobs per CPU instead of only one, cutting down on time to run a script.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

What is $1 and $2 in bash?

$1 is the first argument (filename1) $2 is the second argument (dir1)


1 Answers

Bash doesn't support threading per se, but you could launch multiple java processes in the background, like:

java myprog & java myprog & java myprog & 

Anything more than that you might look into Python or Ruby, which have thread management utilities, you could wait for each one to finish and collect output/exit status, etc.

Edit: Borrowing the suggestion from @CédricJulien to use wait, here's a more thorough example. Given this MyProg.java program:

public class MyProg {     public static void main(String[] args) {         System.exit(Integer.parseInt(args[0]));     } } 

you could write the following bash-threads.sh script to launch multiple instances of it in parallel:

#!/bin/bash set -o errexit  java MyProg 1 & pid1=$! java MyProg 0 & pid2=$! java MyProg 2 & pid3=$!  wait $pid1 && echo "pid1 exited normally" || echo "pid1 exited abnormally with status $?" wait $pid2 && echo "pid2 exited normally" || echo "pid2 exited abnormally with status $?" wait $pid3 && echo "pid3 exited normally" || echo "pid3 exited abnormally with status $?" 

Its output is:

pid1 exited abnormally with status 1 pid2 exited normally pid3 exited abnormally with status 2 
like image 112
Steve Kehlet Avatar answered Sep 23 '22 13:09

Steve Kehlet