Shell implementation Multi-threaded (multi-tasking)

Source: Internet
Author: User

Implementation scenario: 1. Add:& at the end of the command
#/bin/Bashall_num=Tena=$(Date+%h%m%S) forNuminch`seq 1${all_num} ' Do {    Sleep 1    Echo${num}}& Doneb=$(Date+%h%m%S)Echo-E"starttime:\t$a"Echo-E"endtime:\t$b"

With the & symbol at the end of the command, the command executes in the background so that subsequent commands do not have to wait for the command to finish before starting execution.

2. Resolve the main thread early exit problem, add wait
#/bin/Bashall_num=Tena=$(Date+%h%m%S) forNuminch`seq 1${all_num} ' Do {    Sleep 1    Echo${num}}&# The command is executed in the background and the command range is surrounded by {} Done# Wait for the child process to end under the current script processwaitb=$(Date+%h%m%S)Echo-E"starttime:\t$a"Echo-E"endtime:\t$b"
3. Control the number of background executions (number of threads), Mkfifo
#/bin/Bashall_num=Ten# Set the number of concurrent processes Thread_num=5a=$(Date+%h%m%S) #MkfifoTempfifo="My_temp_fifo"Mkfifo${tempfifo}# to make file descriptors non-blocking exec6<>${tempfifo}RM-f ${tempfifo}# Creating placeholder information for file descriptors for((i=1; i<=${thread_num};i++)) Do{    Echo } Done>&6 #  forNuminch`seq 1${all_num} ' Do{Read-U6 {Sleep 1        Echo${num}Echo "">&6    } & }  Done wait# close FD6 pipe exec6>&-b=$(Date+%h%m%S)Echo-E"starttime:\t$a"Echo-E"endtime:\t$b"
Resources

[1] Scenario Linux--shell How to achieve multithreading?

[2] linux-shell-using Mkfifo for multitasking concurrency and concurrency control

Shell implementation Multi-threaded (multi-tasking)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.