Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a JoinHandle from a function?

What is the best way to handle a situation like this:

use std::thread;

struct Prefe;

fn main() {
    let prefe = Prefe;

    start(&prefe).join();
}

fn start(pre: &Prefe) -> thread::JoinHandle {
    thread::spawn(move || {
        println!("Test spawn");
    })
}

I get the error:

error[E0243]: wrong number of type arguments: expected 1, found 0
  --> src/main.rs:11:26
   |
11 | fn start(pre: &Prefe) -> thread::JoinHandle {
   |                          ^^^^^^^^^^^^^^^^^^ expected 1 type argument

I think I could use something like this, but I do not know what to use for T:

fn start<T>(pre: &Prefe, t: T) -> thread::JoinHandle<T> {
    thread::spawn(move || {
        println!("Test spawn");
    })
}

I see that thread::spawn uses this to return, but I do not know if this can help me or how to use it:

Builder::new().spawn(f).unwrap()

This seems to work, but I do not know if this is the right or wrong way:

fn start(pre: &Prefe) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        println!("Test spawn");
    })
}
like image 323
Angel Angel Avatar asked May 08 '17 00:05

Angel Angel


People also ask

What is JoinHandle in Rust?

A JoinHandle detaches the associated thread when it is dropped, which means that there is no longer any handle to the thread and no way to join on it. Due to platform restrictions, it is not possible to Clone this handle: the ability to join a thread is a uniquely-owned permission.


1 Answers

Review the function signature of thread::spawn:

pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
    F: FnOnce() -> T,
    F: Send + 'static,
    T: Send + 'static,

This says that spawn takes a generic type F. This type must implement the trait FnOnce. That implementation takes no arguments and returns an argument of type T. spawn returns a JoinHandle that is parameterized with the same type T.

To use this information, you need to know what type your closure returns. Once you know that, that is the type that your JoinHandle should be parameterized with.

Your example closure calls println! which has a return type of (), so that is what this JoinHandle would use.

like image 149
Shepmaster Avatar answered Sep 29 '22 15:09

Shepmaster