FAQ - Help and questions

How do I fix "closure may outlive the current function" with thread::spawn (E0373)?

#errors#threads#closurespublished 3 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

A spawned thread can run longer than the function that started it, so it cannot borrow that function's variables. Add move before the closure so the thread owns what it uses. To share one value between threads, use Arc and clone it per thread. Scoped threads may borrow, because they end before the function does.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

thread::spawn needs a closure that is valid for the whole life of the thread, which the compiler cannot bound. A closure that merely borrows name could be running after name is freed. Ownership has to move into the thread.

src/main.rsrust
use std::thread;

fn main() {
    let name = String::from("Ada");
    let handle = thread::spawn(|| {
        println!("hello, {name}");
    });
    handle.join().unwrap();
}
text
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
 --> src/main.rs:5:32
  |
5 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `name`
6 |         println!("hello, {name}");
  |                           ---- `name` is borrowed here
  |
note: function requires argument type to outlive `'static`
 --> src/main.rs:5:18
  |
5 |       let handle = thread::spawn(|| {
  |  __________________^
6 | |         println!("hello, {name}");
7 | |     });
  | |______^
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
  |
5 |     let handle = thread::spawn(move || {
  |                                ++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0373`.

The answers below are the valid ways out.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    3 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: move the value in#

    The compiler's own suggestion. After move, the closure owns name and the main function can no longer use it.

    src/main.rsrust
    use std::thread;
    
    fn main() {
        let name = String::from("Ada");
        let handle = thread::spawn(move || {
            println!("hello, {name}");
        });
        handle.join().unwrap();
    }
    text
    hello, Ada
      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: share with Arc#

      When several threads need the same data, put it in an Arc and give each thread its own clone of the pointer: let name = Arc::clone(&name); before the move closure. Add a Mutex inside the Arc if they must change it. See the thread on Box, Rc, Arc and Mutex.

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail
        #4

        Approach 3: scoped threads#

        std::thread::scope guarantees that every thread started inside it ends before the scope does, so these threads may borrow local variables with no move and no Arc:

        rust
        let name = String::from("Ada");
        std::thread::scope(|s| {
            s.spawn(|| println!("hello, {name}"));
        });
        println!("{name} is still ours");

        Best when: the work is a fork and join inside one function.

        Common mistakes#

        • Adding move and then using the variable afterwards ("borrow of moved value"). Clone it first or use Arc.
        • Forgetting handle.join(). Without it, main may end before the thread prints anything.
          QuoteReply
          Share
          Hacker NewsRedditLinkedInE-mail