This article mainly describes how to use bash to implement a basic thread pool.
1. Pre-knowledge
2. Realization of Ideas
There are many ways to implement a process pool, such as creating a file to determine the number of files. In this paper, we use FIFO file to implement thread pool, and use the Read command of Linux in the natural blocking to implement quickly.
3. Concrete implementation
Create process_pool.sh with the following script:
#!/bin/bash #线程池process_pool () { #判断输入参数等 if [ $# -lt 3 ]; then echo "$0 process_ Num command [args] " return 1 fi _process_num=$1 shift _func=$1 shift if [[ ! $_process_num =~ ^[0-9]+ $ ]]; then echo "Process_num must be a number " return 1 fi if !type $_func >/dev/null 2>&1; then echo "Comannd must be executable" return 1 fi # Create a FIFO pipeline file fifo= "/tmp/$$.fifo" mkfifo $fifo #创建一个文件描述符号, Associating FD with this file descriptor to this file &NBSP;&NBSP;&NBSP;&NBSP;#{FD} represents a non-display descriptor exec {FD}<> $fifo rm $fifo # Create slots for i in $ (Seq $_process_num); do echo >& $FD done # Execute specific Commands for arg in [email protected]; do read -u $FD { $_func $arg echo >& $FD }& Done # wait wait for all background processes to complete wait # Release File descriptor exec {FD}>&-} #以下为测试test () { echo $1 sleep 3 return 0} process_pool 3 ' Test ' 1 2 3 4 5 6 7
Already at the end there is a basic test case, just
SH process_pool.sh
You can see the effect.
This article is from the "xlows" blog, make sure to keep this source http://xlows.blog.51cto.com/5380484/1773678
How to implement a basic thread pool with the shell