Hey everyone, first time poster. I'm writing my own simple thread pool that adds jobs as closures to a queue and then executes them across any number of threads synchronously.
I got this to work defining a Job struct that stores the type:
Box<Fn() + Send + Sync>
It works, but a user still has to explicitly type out something like this:
Job::new( Box::new ( move || {
//blah blah
} ) );
I want to eliminate the necessity to explicitly "Box" the closure, like what I imagine thread::spawn() does - but maybe I'm wrong on that. Is there some trick to allow my new() function to automatically convert this closure argument into a boxed closure behind the scenes?
I think the main problem here is that you're using trait objects without really knowing, or maybe you did but haven't considered the possibility of using a generic and then boxing it like @RustyYato does in their post. In the future, please use the dyn keyword to denote trait objects, like so:
@RustyYato Thanks for your answer! Using your suggestion of a generic that is then boxed in the new function, I got it to work as I was hoping to! I was messing around with boxing it in the new function, but it was the declaration of a generic type that I was missing, and it now compiles as long as I add the 'static lifetime specification like so
Is this consistent with your understanding? Lifetimes remain a challenge for me in most cases...
@OptimisticPeach Thank you for your explanation and another option. I was most certainly using trait objects without knowing it, but I can see that now and everything about it makes a lot more sense. Thanks!
Thank you both for your quick and helpful answers!