在循环中使用bash等待 [英] Use bash wait in for-loop

查看:82
本文介绍了在循环中使用bash等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我已经搜索并期望这个问题以前曾被问过,但尽管有很多类似的问题,但找不到类似的东西)

(I have searched and expected this question to have been asked before but couldn't find anything like this although there are plenty of similar questions)

我希望此for循环在3个不同的线程/进程中运行,并且 wait 似乎是正确的命令

I want this for-loop to run in 3 different threads/processes and wait seem to be the right command

for file in 1.txt 2.txt 3.text 4.txt 5.txt
        do something lengthy &
        i=$((i + 1))
        wait $!
done

但是,我想这个构造只是启动一个线程,然后等到完成后再启动下一个线程.我可以将 wait 放置在循环之外,但是我该怎么办

But this construct, I guess, just starts one thread and then wait until it is done before it starts the next thread. I could place wait outside the loop but how do I then

  1. 访问PID?
  2. 将其限制为3个线程吗?

推荐答案

内置的 jobs 可以列出当前正在运行的后台作业,因此您可以使用它来限制创建的作业数.要将工作限制为三个,请尝试如下操作:

The jobs builtin can list the currently running background jobs, so you can use that to limit how many you create. To limit your jobs to three, try something like this:

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

这篇关于在循环中使用bash等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆