linux - 为什么 "while"并发在 shell 脚本中运行越来越慢?

标签 linux shell

我想像这样使用 shell 的并发函数一次使​​用更多 cpu 压缩大量文件:

#!/bin/bash
#set -x

function zip_data()
{
while true
do
{
echo "do zip something" 
}&
done
}

zip_data  
wait

开始时,循环一次的速度很快。 但是随着运行时循环次数的增加, 速度越来越慢。 为什么???

我认为原因可能是有太多的子进程在运行。 所以我尝试让 while 函数像这样一次运行一个循环:

#!/bin/bash
#set -x

function trap_exit
{
exec 1000>&-;exec 1000<&-
kill -9 0
}

trap 'trap_exit; exit 2' 1 2 3 15 9

mkfifo testfifo ; exec 1000<>testfifo ; rm -rf testfifo

function zip_data()
{
echo >&1000

while true
read -u 1000
do
{
echo "do something" 
echo >&1000 
}&
done
}

zip_data 
wait

不过现象和以前一样。

所以我不明白为什么跑的时候速度越来越慢。

#

今天我这样尝试,但它不起作用

#!/bin/bash
#set -x
c=0
while true
do
        c=$(jobs -p | wc -l)
        while [ $c -ge 20 ]; do
                c=$(jobs -p | wc -l)
                sleep 0.01
        done

        {
        echo "$c" 
        sleep 0.8
        }&


done

所以我尝试其他方式来完成这个功能,谢谢!

#!/bin/bash
#set -x

function EXPECT_FUNC()
{
para=$1 
while true
do
{
do something $1
}
done

}

EXPECT_FUNC 1 &
EXPECT_FUNC 2 &
EXPECT_FUNC 3 &
EXPECT_FUNC 4 &


wait

最佳答案

任何单线程实用程序都可以在管理良好的并发线程中运行 parallel . man parallel 提供了数十个示例,例如:

   Create a directory for each zip-file and unzip it in that dir:

       parallel 'mkdir {.}; cd {.}; unzip ../{}' ::: *.zip

   Recompress all .gz files in current directory using bzip2 running 1 job
   per CPU core in parallel:

       parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz

一个仅适用于 gzip 的特别有趣的示例展示了如何使用多个 CPU 同时处理 一个 存档,单线程归档器,这听起来不可能:

    To process a big file or some output you can use --pipe to split up 
    the data into blocks and pipe the blocks into the processing program.

    If the program is gzip -9 you can do:

        cat bigfile | parallel --pipe --recend '' -k gzip -9 >bigfile.gz

    This will split bigfile into blocks of 1 MB and pass that to 
    gzip -9 in parallel. One gzip will be run per CPU core. The output
    of gzip -9 will be kept in order and saved to bigfile.gz

如果 parallel 太复杂,这里有一些内置并行归档的压缩工具:

关于linux - 为什么 "while"并发在 shell 脚本中运行越来越慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168431/

相关文章:

linux - 脚本中 $(command) 和 `command` 之间的区别

linux - 使用单独文件中的 sed

linux - Shell脚本是否足够?

linux - 安装依赖 SciKit/NumPy/SciPy

mysql - 通过 Shell 更新 Root 密码

java - 如何使用java在不同机器上执行shell脚本

linux - 为什么使用 "set var = value"采购脚本会破坏 $@?

linux - 想要制作一个shell脚本

linux - gRPC + SSL + uber jar + Linux = 加载 netty-tcnative 失败

android - linux下为android搭建openh264