Clone/copy func


#1

https://play.rust-lang.org/?gist=252578d763420f278339724606f9b27a&version=nightly

how do I make this work?

normally I would clone the object, but I don’t know how that goes in rust with function.
can I create a new func on runtime which executes dick.func?

its possible with mutex (frm panicbit on irc), but thats unnecessary overhead that doesnt fit in my app
https://play.rust-lang.org/?gist=0de136d2073e0642440e93194d132391


#2

Do you need to retain a reference to the original object in the first thread? If not, you can just do thread::spawn(move || (dick.func)());.

The issue here is that you’re making a copy of Dick on the stack then sending a reference to it to another thread, which may or may not use the Dick after the current function returns. Which would give you dangling pointer issues. The only way to solve this (which wouldn’t result in memory errors) is with some sort of synchronization mechanism like Arc or Mutex. Otherwise you could use crossbeam and its scoped thread to ensure your Dick outlives the spawned thread and closure.


#3

hm, thats unfortunate. I actually want to use futures_cpupool not just a thread, hence crossbeam is not a fit. and I want to call dick.func() multiple times (didnt add that in the first post, sorry), so cant use move.

i wish i could just ignore this, rust safety kinda sucks sometimes

thank you


#4

Can you create an instance of your struct each time you need to send it to a threadpool? So you’d move each one into the closure. If the construction of it is cheap, then this shouldn’t be an issue.

Also, any reason you’re using a boxed closure? If you went with a generic struct you could avoid the heap allocation there.


#5

I think I use Box because I put my Dicks in a struct (in the non reduced code) on a Vec field and the compile time size is unknown. I know little about Generic (structs) and in my efforts to try compiler still complains about compile time size unknown + code looks disgusting.

how do i create such a instance? I’d only have another instance available to create it from (a Dick). this is actually supposed to be a library and a library consumer shall pass the function and the library accepts the function and executes it.


#6

Ah yeah, if you’re storing in a vec then you’re dealing with trait objects and need type erasure.

If you only have another instance to clone from, then you’ll need to Clone unfortunately. Do you need FnMut though? If you don’t, a simple Arc wrapping the closure should suffice - you can then implement Clone by cloning the Arc.