Created
August 27, 2020 15:40
-
-
Save eliaskousk/4e1cbb321ec9d9638a4e057987f14308 to your computer and use it in GitHub Desktop.
Test Threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// This simple program spawns a specified number of threads | |
// that execute a heavy calculation | |
// for a specified amount of time in seconds | |
// | |
// Usage: ./test-threads [NUM_THREADS, default is 2] [TIME_LIMIT, default is 10] | |
// | |
use std::env; | |
use std::thread; | |
use std::time::{Duration, Instant}; | |
const DEF_NTHREADS : u32 = 2; | |
const MAX_NTHREADS : u32= 8; | |
const DEF_TLIMIT : u32 = 10; | |
const MAX_TLIMIT : u32 = 60; | |
fn heavy_calculation(i : u32) -> f64 { | |
(i as f64 + 1.0) * 5.0 * 7.0 / 1324.0 * 13244.0 * 77.0 | |
} | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let mut num_threads = DEF_NTHREADS; | |
if args.len() > 1 { | |
num_threads = args[1].trim().parse() | |
.expect("Please provide number of threads."); | |
if num_threads > MAX_NTHREADS { | |
num_threads = MAX_NTHREADS; | |
} | |
} | |
let mut time_limit = DEF_TLIMIT; | |
if args.len() > 2 { | |
time_limit = args[2].trim().parse() | |
.expect("Please provide time limit in seconds."); | |
if time_limit > MAX_TLIMIT { | |
time_limit = MAX_TLIMIT; | |
} | |
} | |
println!("Main thread will now spawn {} children threads for {} seconds.", | |
num_threads, time_limit); | |
let mut children = vec![]; | |
for i in 0..num_threads { | |
children.push(thread::spawn(move || { | |
println!("Children thread {} starting the heavy calculation.", i); | |
let start = Instant::now(); | |
let mut result = 0.0; | |
while start.elapsed() < Duration::from_secs(time_limit.into()) { | |
result += heavy_calculation(i); | |
} | |
println!("Children thread {} finished. Result was: {}.", i, result); | |
result | |
})); | |
} | |
println!("Main thread will now wait for children threads."); | |
let mut total = 0.0; | |
for child in children { total += child.join().unwrap(); } | |
println!("Main thread will now exit. Total result was: {}.", total); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment