Guest User

Untitled

a guest
Oct 18th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. fn do_partial_sum(start: i64, to_do: i64) -> i64 {
  2. let mut result = 0;
  3. for i in start..(start + to_do) {
  4. if i % 2 == 0 {
  5. result += i;
  6. }
  7. }
  8. result
  9. }
  10.  
  11. const MAX: i64 = 2000000000;
  12.  
  13. fn main() {
  14. let thread_count = 4;
  15. let mut result;
  16. if thread_count == 0 {
  17. result = do_partial_sum(0, MAX);
  18. } else {
  19. let each = {
  20. let c = thread_count as i64;
  21. (MAX + c - 1) / c
  22. };
  23. let mut threads = Vec::new();
  24. result = 0;
  25. let mut start = 0;
  26. while start < MAX {
  27. let result_ptr = &mut result;
  28. threads.push(std::thread::spawn(move || {
  29. let incr = if each + start > MAX { MAX - start } else { each };
  30. *result_ptr += do_partial_sum(start, incr);
  31. }));
  32. start += each;
  33. }
  34. for t in threads {
  35. t.join().unwrap();
  36. }
  37. }
  38.  
  39. println!("result: {}", result);
  40. }
Add Comment
Please, Sign In to add comment