(我已经搜索过,并且预计这个问题之前会被问过,但是虽然有很多类似的问题但是找不到这样的问题)
我希望这个for循环在3个不同的线程/进程中运行,wait似乎是正确的命令
for file in 1.txt 2.txt 3.text 4.txt 5.txt
do something lengthy &
i=$((i + 1))
wait $!
done
Run Code Online (Sandbox Code Playgroud)
但是,我想这个构造只是启动一个线程,然后等到它完成它才启动下一个线程.我可以放在wait循环之外,但我怎么办呢
该jobs内置函数可以列出当前正在运行的后台作业,因此您可以使用它来限制创建的数量。要将您的工作限制为三项,请尝试以下操作:
for file in 1.txt 2.txt 3.txt 4.txt 5.txt; do
if [ $(jobs -r | wc -l) -ge 3 ]; then
wait $(jobs -r -p | head -1)
fi
# Start a slow background job here:
(echo Begin processing $file; sleep 10; echo Done with $file)&
done
wait # wait for the last jobs to finish
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |