Skip to content

How to handle join when it's called from the associated thread? #43539

Closed
@BusyJay

Description

@BusyJay

Considering following snippets:

use std::thread::{self, JoinHandle};
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel::<JoinHandle<()>>();
    let j = thread::spawn(move || {
        while let Ok(h) = rx.recv() {
            h.join().unwrap();
        }
    });
    tx.send(j).unwrap();
    thread::sleep_ms(1000);
}

Currently on linux, the spawned thread will just panic at option unwrap which happen inside std library:

thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', /checkout/src/libcore/option.rs:335
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
stack backtrace:
   0: std::sys::imp::backtrace::tracing::imp::unwind_backtrace
             at /checkout/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:49
   1: std::sys_common::backtrace::_print
             at /checkout/src/libstd/sys_common/backtrace.rs:71
   2: std::panicking::default_hook::{{closure}}
             at /checkout/src/libstd/sys_common/backtrace.rs:60
             at /checkout/src/libstd/panicking.rs:355
   3: std::panicking::default_hook
             at /checkout/src/libstd/panicking.rs:371
   4: std::panicking::rust_panic_with_hook
             at /checkout/src/libstd/panicking.rs:549
   5: std::panicking::begin_panic
             at /checkout/src/libstd/panicking.rs:511
   6: std::panicking::begin_panic_fmt
             at /checkout/src/libstd/panicking.rs:495
   7: rust_begin_unwind
             at /checkout/src/libstd/panicking.rs:471
   8: core::panicking::panic_fmt
             at /checkout/src/libcore/panicking.rs:69
   9: core::panicking::panic
             at /checkout/src/libcore/panicking.rs:49
  10: <core::option::Option<T>>::unwrap
  11: <std::thread::JoinInner<T>>::join
  12: <std::thread::JoinHandle<T>>::join
  13: testjoin::main::{{closure}}

It makes no sense to call join inside the associated thread, but a meaningless panic is sure not the good way to handle this situation. Maybe we should return an error which contains the join handle, so the caller can recover the failure. If panic is preferred, then a more friendly message should be good for users.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions