Created
February 24, 2019 01:42
-
-
Save unrealhoang/8b1ffa00cbe293fc9d42613bd971f5a0 to your computer and use it in GitHub Desktop.
Parallel sum
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
use std::thread; | |
use std::sync::atomic::AtomicUsize; | |
use std::sync::atomic::Ordering; | |
use std::sync::Arc; | |
const MOD:u64 = 123456789; | |
// change to stack based for lower stack overhead | |
fn powmod(n: u64, p: u64, m: u64) -> u64 { | |
if p == 0 { | |
return 1; | |
} | |
if p == 1 { | |
return n % m; | |
} | |
let t = powmod(n, p / 2, m); | |
if p % 2 == 1 { | |
return (((t * t) % m) * n) % m; | |
} else { | |
return (t * t) % m; | |
} | |
} | |
fn main() { | |
let count_lock = Arc::new(AtomicUsize::new(1)); | |
let num_worker = 4; | |
let n = 50_000_000; | |
let mut workers = Vec::new(); | |
for i in (0..num_worker) { | |
let lock = Arc::clone(&count_lock); | |
let thread = thread::spawn(move || { | |
let mut sum = 0; | |
loop { | |
let acquired = lock.fetch_add(1, Ordering::SeqCst) as u64; | |
if acquired > n { | |
break | |
} | |
sum = (sum + powmod(acquired, acquired, MOD)) % MOD; | |
} | |
sum | |
}); | |
workers.push(thread); | |
} | |
let mut total_sum = 0; | |
for w in workers { | |
total_sum = (total_sum + w.join().expect("thread result error")) % MOD; | |
} | |
println!("Total sum: {}", total_sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment