How to achieve multi-threaded programming under Linux shell

  
                

Linux multi-threaded programming has the advantages of improving application response and making multi-cpu system more effective. The following small series will explain the multi-thread programming process through the shell multi-thread programming example under Linux. Let's go.

#! /bin/bash

#———————————————————&mdash ;———————–

# This example illustrates a technique for simulating multithreading with the wait and read commands

# this Techniques are often used for multi-host checks, such as ssh login, ping, etc. This single process is slow and does not consume CPU.

# Also illustrates multi-threaded control

#— & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; & mdash; —–

function a_sub

# Define a function here as a thread (child process)

sleep 3 #thread The effect is sleep 3s

}

tmp_fifofile=“/tmp/$.fifo” mkfifo $tmp_fifofile # Create a new fifo type file

Exec 6 ""$tmp_fifofile # Point fd6 to fifo type

rm $tmp_fifofile thread=15 # Define the number of threads here

for

((i=0;i "$thread;i++));do echo

done 》&6 # In fact, put $thread carriage return in fd6

for

( (i=0;i "50;i++));do #50 cycles, can be understood as 50 hosts, or other

read -u6 # A read -u6 command is executed once, from fd6 Subtract a carriage return and then execute it downwards.

# When there is no carriage return in fd6, it stops here, thus achieving thread number control

{ # here The process starts executing and is placed in the background

a_sub &&

{ # Here can be used to determine the logic of the child process

echo “a_sub is finished”

}

Copyright © Windows knowledge All Rights Reserved