Linux Bash 中的多线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2425870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:51:49  来源:igfitidea点击:

Multithreading in Bash

linuxmultithreadingbashshell

提问by Kiran

I would like to introduce multithreading feature in my shell script.

我想在我的 shell 脚本中引入多线程功能。

I have a script which calls the function read_cfg()with different arguments. Each of these function calls are independent.

我有一个脚本,它read_cfg()使用不同的参数调用函数。这些函数调用中的每一个都是独立的。

Would it be possible to instantiate these function calls (not scripts) parallelly. Please let me how can we achieve that.. ?

是否可以并行实例化这些函数调用(不是脚本)。请让我如何实现..?

采纳答案by Martin

Sure, just add &after the command:

当然,只需&在命令后添加:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional waitcommand will then wait for all the jobs to finish.

然后所有这些作业将同时在后台运行。然后可选wait命令将等待所有作业完成。

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

每个命令都将在单独的进程中运行,因此从技术上讲它不是“多线程”,但我相信它可以解决您的问题。

回答by mouviciel

Bash job control involves multiple processes, not multiple threads.

Bash 作业控制涉及多个进程,而不是多个线程。

You can execute a command in background with the &suffix.

您可以在后台执行带有&后缀的命令。

You can wait for completion of a background command with the waitcommand.

您可以使用该wait命令等待后台命令完成。

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of |is connected to stdin of command at right.

您可以通过将多个命令用 分隔来并行执行多个命令|。这也提供了一种同步机制,因为左侧命令的标准输出|连接到右侧命令的标准输入。

回答by tnorgd

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

您可以并行运行脚本的多个副本,每个副本用于不同的输入数据,例如处理 4 个内核上的所有 *.cfg 文件:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

read_cfg.sh 脚本只接受一个参数(由 -n 强制执行)