Linux bash 中的线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6156541/
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-05 04:18:33  来源:igfitidea点击:

Threads in bash?

linuxbashterminal

提问by auwall

Is it possible to use threads in bash scripts. I have a driver class in java that i'm trying to run multiple instances of at the same time. The only way i know to do this is make threads in bash, but i'm not sure if thats even possible. Any help would be appreciated

是否可以在 bash 脚本中使用线程。我在 java 中有一个驱动程序类,我试图同时运行多个实例。我知道这样做的唯一方法是在 bash 中创建线程,但我不确定这是否可能。任何帮助,将不胜感激

采纳答案by Steve Kehlet

Bash doesn't support threading per se, but you could launch multiple java processes in the background, like:

Bash 本身不支持线程,但您可以在后台启动多个 java 进程,例如:

java myprog &
java myprog &
java myprog &

Anything more than that you might look into Python or Ruby, which have thread management utilities, you could wait for each one to finish and collect output/exit status, etc.

除此之外,您可能会查看 Python 或 Ruby,它们具有线程管理实用程序,您可以等待每个程序完成并收集输出/退出状态等。

Edit: Borrowing the suggestion from @CédricJulien to use wait, here's a more thorough example. Given this MyProg.javaprogram:

编辑:借用@CédricJulien 的建议使用wait,这里有一个更彻底的例子。鉴于此MyProg.java程序:

public class MyProg {
    public static void main(String[] args) {
        System.exit(Integer.parseInt(args[0]));
    }
}

you could write the following bash-threads.shscript to launch multiple instances of it in parallel:

您可以编写以下bash-threads.sh脚本来并行启动它的多个实例:

#!/bin/bash
set -o errexit

java MyProg 1 &
pid1=$!
java MyProg 0 &
pid2=$!
java MyProg 2 &
pid3=$!

wait $pid1 && echo "pid1 exited normally" || echo "pid1 exited abnormally with status $?"
wait $pid2 && echo "pid2 exited normally" || echo "pid2 exited abnormally with status $?"
wait $pid3 && echo "pid3 exited normally" || echo "pid3 exited abnormally with status $?"

Its output is:

它的输出是:

pid1 exited abnormally with status 1
pid2 exited normally
pid3 exited abnormally with status 2

回答by Cédric Julien

You won't be able to launch some "bash threads", but you can launch subprocesses in bash, just using the &after the command, and it will launch it in a background process.

您将无法启动一些“bash 线程”,但您可以在 bash 中启动子&进程,只需使用after 命令,它将在后台进程中启动它。

Call a waitafter launching your processes to wait for them to be finished.

wait启动进程后调用 a以等待它们完成。

Try this

尝试这个

first_command &
second_command &

wait