threads in bash

Here an easy script for using threads in bash

#!/bin/bash

threads=4

thread(){
  echo "thread $$ started with param $1"
  sleep 10  # do stuff
}

selfcount(){ echo $(( $(ps -ef|grep -v grep|grep -c $0) - 3 )); }

for i in {1..100}; do   # worktasks
  while [[ $(selfcount) -ge $threads ]]; do
    sleep 0.1
  done
  thread $i &   # call thread in background
  sleep 0.1
done

while [[ $(selfcount) > 0 ]]; do sleep 0.1; done # wait for the last threads to finish

Leave a Reply

Your email address will not be published. Required fields are marked *