There is no real multi-threading in the shell, and to implement multithreading you can start multiple back-end processes to maximize CPU Performance.
Look directly at the code Example.
(1) Sequential execution of code
1#!/bin/Bash2 Date3 forIinch`seq 1 5`4 do5 {6 Echo "Sleep 5"7 Sleep 58 }9 doneTen Date
Output:
+ :5sleep5 sleep 5 Sleep 5 Sleep 5 from: £º
(2) Parallel Code
Implementing a "multi-process" implementation using ' & ' +wait
1#!/bin/Bash2 Date3 forIinch`seq 1 5`4 do5 {6 Echo "Sleep 5"7 Sleep 58 } &9 doneTen wait# #等待所有子后台进程结束 one Date
Output:
+ : Sleep5sleep5 sleep 5 Sleep 5 Sleep 5 from: £º
(3) how many processing tasks can be achieved to enable the number of background processes to be controlled?
A simple method can be implemented using a 2-layer for/while loop, where multiple daemon executions of the wait-time inner loop are completed .
however, the problem with this approach is that if the inner loop has a "slow node" , it may result in a long execution time for the entire Task.
More advanced implementations can see (4)
(4) a named pipe (fifo) is used to achieve a controlled number of background processes per Start.
1#!/bin/Bash2 3 functionmy_cmd () {4t=$RANDOM5t=$[t% the]6 Sleep$t7 Echo "Sleep $t S"8 }9 Tentmp_fifofile="/tmp/$$.fifo" one Mkfifo$tmp _fifofile # Create a new Fifo-type file aExec6<>$tmp _fifofile # fd6 point to FIFO type - RM$tmp _fifofile #删也可以 - thethread_num=5# Maximum number of simultaneous threads to execute -job_num= -# Total Tasks - - #根据线程总数量设置令牌个数 + for((i=0; i<${thread_num};i++)); do - Echo + done>&6 a at for((i=0; i<${job_num};i++)); do# Number of tasks -# a read-the U6 Command executes once, subtracts a carriage return from the fd6, and then executes down, - # When there is no carriage return in the fd6, it stops here, allowing for a thread count control -read-U6 - - #可以把具体的需要执行的命令封装成一个函数 in { - My_cmd to} & + - Echo>&6# when the process is finished, add a carriage return to the fd6, that is, fill in the read-U6 minus that One. the done * $ waitPanax NotoginsengExec6>&-# Close Fd6 - Echo " over"
Reference: http://lawrence-zxc.github.io/2012/06/16/shell-thread/
Linux Shell multithreaded Execution program