rust-lang / rust-lang/rust

Feature request: Function to join thread with timeout

Open
#126,972 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

A somewhat niche, but still occasionally useful feature is the ability to join a thread with a timeout, i.e. wait for a thread to join until a timeout is reached. It would be nice if this was included in the standard library, since trying to write an external crate for this is fairly convaluted, because the thread management logic is tightly coupled to the standard library.

I propose adding a function that allows this to std::thread::JoinHandle and std::thread::ScopedJoinHandle.
The API could look approximately like this:

impl<T> JoinHandle<T> {
    pub fn join_timeout(self, duration: Duration) -> Result<T, JoinTimeoutError<T>> {
        todo!()
    }
}

pub enum JoinTimeoutError<T> {
    Panic(Box<dyn Any + Send + 'static>),
    Timeout(JoinHandle<T>),
}

Returning the JoinHandle on timeout might be a little clunky, but it is the only way I could think of to enforce that join_timeout isn't called again after it succeeds. Alternatively join_timeout could take &mut self and then return a third enum variant or panic to indicate that the thread has already been joined.

I don't know how difficult this would be to implement for all supported platforms, but similar functions are included in (among others) Python, Java, C# and POSIX threads, so it should at least be possible on all major platforms.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the std:🧵:JoinHandle and std:🧵:ScopedJoinHandle entry points described in the issue, then review how thread joining is handled across supported platforms. Resolve the timeout API and error behavior, including what happens after a timeout, and ensure the feature works consistently on those platforms.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
operating-systems
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.