#Spawn thread within struct

5 messages · Page 1 of 1 (latest)

woven oracle
#

the move there is doing nothing because you cant move from behind a reference

green wharf
#

In order for the thread to be able to operate on self, self has to live forever ('static)

#

If self didn't live forever, what should the thread do once self disappears?

finite pier
#

std::thread::spawn() takes a FnOnce with Send and 'static bounds. FnOnce and Send cause no problems here, but the 'static bound means that the callable type you pass in mustn't contain any types with lifetime bounds more restrictive than 'static. The closure you pass captures self, which is a &'_ mut ZMQ. This implicit '_ lifetime (you could call it 'a or anything you like) doesn't satisfy a 'static bound because only 'static itself does; 'static outlives everything and is thus the most permissive when you have it, and the most restrictive when you require it.

This 'static bound exists because the lifetime of the spawned thread is potentially unbounded. You could leak the thread's handle and never join it and Rust has no way of enforcing that you don't do this, so the requirement exists that whatever your closure depends on is valid forever, even if the thread outlives main().

You can often solve this problem by capturing by move (via the move keyword you're already using) since owned values satisfy the 'static bound if they have no more restrictive lifetime bounds themselves, but the reference you capture does have such a more restrictive lifetime bound.

You could have receive() take self by move (pub fn receive(self)), which would solve the problem if consuming self doesn't cause any problems itself. Otherwise, you could clone an Arc<Mutex<ZMQ>> and pass one of the clones to the new thread, or use a scoped thread to allow spawning threads with a lifetime bound matching the lifetime of the scope, rather than 'static.

green wharf