Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn do_partial_sum(start: i64, to_do: i64) -> i64 {
- let mut result = 0;
- for i in start..(start + to_do) {
- if i % 2 == 0 {
- result += i;
- }
- }
- result
- }
- const MAX: i64 = 2000000000;
- fn main() {
- let thread_count = 4;
- let mut result;
- if thread_count == 0 {
- result = do_partial_sum(0, MAX);
- } else {
- let each = {
- let c = thread_count as i64;
- (MAX + c - 1) / c
- };
- let mut threads = Vec::new();
- result = 0;
- let mut start = 0;
- while start < MAX {
- let result_ptr = &mut result;
- threads.push(std::thread::spawn(move || {
- let incr = if each + start > MAX { MAX - start } else { each };
- *result_ptr += do_partial_sum(start, incr);
- }));
- start += each;
- }
- for t in threads {
- t.join().unwrap();
- }
- }
- println!("result: {}", result);
- }
Add Comment
Please, Sign In to add comment