首先,我将给您一个精简的示例,说明我在几个 linux 脚本中所做的事情。这应该适用于 solaris,但我目前没有任何系统可以测试。我修改了一些使用 /proc 的东西,所以如果有什么不起作用,请告诉我。
#!/bin/bash
# set the max # of threads
max_threads=4
# set the max system load
max_load=4
print_jobs(){
# flush finished jobs messages
jobs > /dev/null
for x in $(jobs -p) ; do
# print all jobs
echo "$x"
done
}
job_count(){
cnt=$(print_jobs $1)
if [ -n "$cnt" ]; then
wc -l <<< "$cnt"
else
echo 0
fi
}
cur_load(){
# get the 1 minute load average integer
uptime |sed 's/.*load average[s]*:[[:space:]]*\([^.]*\)\..*/\1/g'
}
main_function(){
# get current job count and load
jcnow=$(job_count)
loadnow=$(cur_load)
# first, enter a loop waiting for load/threads to be below thresholds
while [ $loadnow -ge $max_load ] || [ $jcnow -ge $max_threads ]; do
if ! [ $firstout ]; then
echo "entering sleep loop. load: $loadnow, threads: $jcnow"
st=$(date +%s)
local firstout=true
else
now=$(date +%s)
# if it's been 5 minutes, echo again:
if [ $(($now - $st)) -ge 300 ]; then
echo "still sleeping. load: $loadnow, threads: $jcnow"
st=$(date +%s)
fi
fi
sleep 5s
# refresh these variables for loop
loadnow=$(cur_load)
jcnow=$(job_count)
unset firstout
done
( ./myjob $@ ) &
}
# do some actual work
for jobparams in "params1" "params2" "params3" "params4" "params5" "params6" "params7" ; do
main_function $jobparams
done
wait
几个警告:
- 你应该捕获信号,这样你就可以杀死子进程。我不知道如何在 solaris 中执行此操作,但这适用于 linux:
trap 'echo "exiting" ; rm -f $lockfile ; kill 0 ; exit' INT TERM EXIT
- 如果在工作已经在运行的情况下负载攀升,则无法进行节流
如果您根本不关心负载,这可能会更简单一些:
#!/bin/bash
# set the max # of threads
max_threads=4
print_jobs(){
# flush finished jobs messages
jobs > /dev/null
for x in $(jobs -p) ; do
# print all jobs
echo "$x"
done
}
job_count(){
cnt=$(print_jobs $1)
if [ -n "$cnt" ]; then
wc -l <<< "$cnt"
else
echo 0
fi
}
main_function(){
# get current job count
jcnow=$(job_count)
# first, enter a loop waiting for threads to be below thresholds
while [ $jcnow -ge $max_threads ]; do
if ! [ $firstout ]; then
echo "entering sleep loop. threads: $jcnow"
st=$(date +%s)
local firstout=true
else
now=$(date +%s)
# if it's been 5 minutes, echo again:
if [ $(($now - $st)) -ge 300 ]; then
echo "still sleeping. threads: $jcnow"
st=$(date +%s)
fi
fi
sleep 5s
# refresh these variables for loop
jcnow=$(job_count)
unset firstout
done
( ./myjob $@ ) &
}
# do some actual work
for jobparams in "params1" "params2" "params3" "params4" "params5" "params6" "params7" ; do
main_function $jobparams
done
wait