Introduction to multi-threaded shell scripts in Linux system

  

Using shell scripts under Linux can easily implement multi-threaded operations. Not only can shell scripts run multi-threads in the background, but also control the number of multi-threads. Let me introduce the multi-threaded shell script under Linux system.

In bash, we run (&) by multi-threaded background.

for((i=1;i“=pairs;i++))

do

mongo=“mongo_00$i”

acmeair_web=  quo;acmeair_web_00$i”

{

docker run --name $mongo -d -p $port_m:27017 mymongodb

docker run -d -p $port: 9080 --name $acmeair_web --link ${mongo}:mongo acmeair/web

} &

((port++))

((port_m++))< Br>

done

wait

We have added { }& so that it can be executed in the background in { }, which is equivalent to the paires executed at the same time, wait is Wait for them to finish.

Above we are all uncontrollable for the number of concurrent, the following implementation is controllable.

tmp_fifofile=“/tmp/$$.fifo”

mkfifo $tmp_fifofile # Create a new fifo type file

exec 6 "" $tmp_fifofile #point fd6 Fifo type

rm $tmp_fifofile

thread = 15 # Define the number of threads here

for ((i=0;i"$thread;i++)); do< Br>

echo

done 》& 6 # In fact, put $thread carriage return in fd6

for ((i=0;i"50;i++ ));do #循环50 times

read -u6 # A read -u6 command is executed once, then a carriage return is subtracted from fd6, and then executed

#fd6 When there is no carriage return, it stops here, thus implementing thread number control

{

{

docker run . . . Mongodb

docker run . . . Acmeair/web

} && {

echo “subprocess is finished”

} | |  {

echo “error”

}

echo 》& 6 # When the process ends, add a carriage return to fd6, that is, make up The one that is read-u6 minus

} &

done

wait #waits all background child processes to end

exec 6》&- #闭fd6

exit 01

The above is a multi-threaded shell script for Linux systems. Of course, running a multi-threaded shell script is only the basis. You can also use multi-threading to program. The specific method can refer to: How to implement shell multi-thread programming under Linux.

Copyright © Windows knowledge All Rights Reserved