course updates

This commit is contained in:
marcel-dempers 2025-03-10 22:08:43 +11:00
parent 2a173123bc
commit e5ccec3c0a
3 changed files with 53 additions and 2 deletions

View File

@ -0,0 +1,30 @@
#!/bin/bash
# Function to simulate CPU usage
simulate_cpu_usage() {
periodInSeconds=$1
core=$2
echo "Simulating CPU usage for $periodInSeconds seconds on core $core..."
end=$((SECONDS + $periodInSeconds))
while [ $SECONDS -lt $end ]; do
# Perform a CPU-intensive task directly in the script
for i in {1..10000}; do
: # No-op command, just to keep the CPU busy
done
done
echo "CPU usage simulation complete on core $core."
}
# Number of CPU cores
num_cores=$(nproc)
# Duration for the simulation
duration=500
# Run the function in the background for each core
for core in $(seq 1 $num_cores); do
simulate_cpu_usage $duration $core &
done
# Wait for all background jobs to complete
wait

View File

@ -0,0 +1,21 @@
#!/bin/bash
# Function to simulate CPU usage
simulate_cpu_usage() {
periodInSeconds=$1
echo "Simulating CPU usage for $periodInSeconds seconds..."
end=$((SECONDS + $periodInSeconds))
while [ $SECONDS -lt $end ]; do
# Perform a CPU-intensive task directly in the script
for i in {1..10000}; do
: # No-op command, just to keep the CPU busy
done
done
echo "CPU usage simulation complete."
}
# Call the function with the provided duration
simulate_cpu_usage 500
#ps -o pid,ppid,cmd --forest -p <PID>

View File

@ -115,13 +115,13 @@ We can take a look at two bash scripts that I have written that demonstrates sin
#### example: single threaded code
If we execute `./singlethread-cpu.sh`, we will notice that only one core of the CPU is busy at a time. </br>
If we execute [./singlethread-cpu.sh](.test/singlethread-cpu.sh), we will notice that only one core of the CPU is busy at a time. </br>
Now because we execute a loop, each iteration of that loop will run on a different core. </br>
Bash itself is single threaded, so this script needs to be optimized if we want to make use of all available CPU cores. </br>
#### example: multi threaded code
If we execute `./multithread-cpu.sh`, we will notice all CPU cores get busy. </br>
If we execute [./multithread-cpu.sh](.test/multithread-cpu.sh), we will notice all CPU cores get busy. </br>
This is because in this script, we read the number of available cores with the `nproc` command. </br>
Then we loop the number of available cores and execute our `simulate_cpu_usage()` function. </br>
At this point it would technically still be single threaded, because it's still a loop and does not create more threads or processes. </br> To get around this we use a special character in bash called `&` at the end of our function. </br>