Advertisement
What42

Multithreaded Rust Code (bad)

Jan 11th, 2023
1,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.28 KB | Source Code | 0 0
  1. pub fn maximum_count_threaded_2 (nums: Vec<i32>, thread_count: usize) -> i32 {
  2.     let mut nums = &*nums;
  3.     let len = nums.len();
  4.     let thread_work_amount = (len + (thread_count - (len - 1) % thread_count + 1)) / thread_count; // trust me this works
  5.     let mut handles = vec!();
  6.     for current_thread_id in 0..thread_count {
  7.         let (current_nums, rest): (&[i32], &[i32]) = if current_thread_id == thread_count - 1 {
  8.             (nums, &[])
  9.         } else {
  10.             nums.split_at(thread_work_amount)
  11.         };
  12.         nums = rest;
  13.         let current_nums: Vec<i32> = current_nums.into();
  14.         let current_handle = thread::spawn(move || {
  15.             let mut positive_count = 0;
  16.             let mut negative_count = 0;
  17.             for v in current_nums {
  18.                 if v > 0 {
  19.                     positive_count += 1;
  20.                 } else if v < 0 {
  21.                     negative_count += 1;
  22.                 }
  23.             }
  24.             (positive_count, negative_count)
  25.         });
  26.         handles.push(current_handle);
  27.     }
  28.     let results = handles.into_iter()
  29.         .map(|handle| handle.join().unwrap_or((0, 0)))
  30.         .fold((0, 0), |(positive_count, negative_count), v| (positive_count + v.0, negative_count + v.1));
  31.     max(results.0, results.1)
  32. }
Tags: rust bad
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement