Reputation: 13
So I want to make a function (which can take some time to complete) run like 100 times at the same time. Using a for loop, it waits till the function is finished before it starts the other one. Here's a sample of what I mean:
sample()
{
echo "start"
echo $1
echo "end"
}
for (( i = 0; i <= 5; i++ )); do
sample $i
done
(yes this is bad code, it's just an example) This will print 1 through 5 with start above it and end below it. It waits until the function is finished before it runs another one. How can I make it so it doesn't wait for the previous function in the loop to finish?
Upvotes: 1
Views: 2542
Reputation: 40224
Use the &
to run the function in background, and the wait
command to wait for them all to finish.
for (( i = 0; i <= 5; i++ )); do
sample $i &
done
wait
Upvotes: 2