rust - How do I use a Condvar to limit multithreading? -
i'm trying use condvar limit number of threads active @ given time , having hard time finding examples on how use condvar. far have:
use std::sync::{arc, mutex, condvar}; use std::thread; fn main() { let thread_count_arc = arc::new((mutex::new(0), condvar::new())); let mut = 0; while < 100 { let thread_count = thread_count_arc.clone(); thread::spawn(move || { let &(ref num, ref cvar) = &*thread_count; { let mut start = num.lock().unwrap(); if *start >= 20 { cvar.wait(start); } *start += 1; } println!("hello"); cvar.notify_one(); }); += 1; } }
the compiler error given is:
<anon>:18:18: 18:23 error: use of moved value: `start` <anon>:18 *start += 1; ^~~~~ <anon>:16:31: 16:36 note: `start` moved here because has type `std::sync::mutex::mutexguard<'_, i32>`, non-copyable <anon>:16 cvar.wait(start); ^~~~~
i'm entirely unsure if use of condvar
correct. tried staying close example on rust api. have suggestions proper way implement this?
here's version compiles:
use std::sync::{arc, mutex, condvar}; use std::thread; fn main() { let thread_count_arc = arc::new((mutex::new(0u8), condvar::new())); let mut = 0; while < 100 { let thread_count = thread_count_arc.clone(); thread::spawn(move || { let &(ref num, ref cvar) = &*thread_count; { let mut start = num.lock().unwrap(); while *start >= 20 { start = cvar.wait(start).unwrap() } *start += 1; } println!("hello"); cvar.notify_one(); }); += 1; } }
the important part can seen wait
api:
fn wait<'a, t>(&self, guard: mutexguard<'a, t>) -> lockresult<mutexguard<'a, t>>
this says wait
consumes guard
, why error did - no longer own start
, can't call methods on it!
this function doing great job of reflecting how condvars work - give lock on mutex (represented start
) while, , when function returns lock again.
the fix give lock , grab lock guard return value wait
. i've switched if
while
, encouraged dbaupp.
Comments
Post a Comment