Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JoinHandle::is_running. #90439

Merged
merged 3 commits into from
Nov 2, 2021
Merged

Conversation

m-ou-se
Copy link
Member

@m-ou-se m-ou-se commented Oct 31, 2021

This adds:

impl<T> JoinHandle<T> {
    /// Checks if the the associated thread is still running its main function.
    ///
    /// This might return `false` for a brief moment after the thread's main
    /// function has returned, but before the thread itself has stopped running.
    pub fn is_running(&self) -> bool;
}

The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information.

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.

@m-ou-se m-ou-se added A-runtime Area: std's runtime and "pre-main" init for handling backtraces, unwinds, stack overflows T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels Oct 31, 2021
@rust-highfive
Copy link
Collaborator

r? @Mark-Simulacrum

(rust-highfive has picked a reviewer for you, use r? to override)

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 31, 2021
@Mark-Simulacrum
Copy link
Member

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.

It feels like instead of a is_running() if, it might be better to add a try_join, like we have https://doc.rust-lang.org/nightly/std/process/struct.Child.html#method.try_wait? That would avoid both essentially checking twice and potentially "missing" the result in some sense since it combines the check with actually getting the results. The described use case at least sounds like it would benefit from try_join rather than is_running, though it's likely to be a small difference in practice.

@m-ou-se
Copy link
Member Author

m-ou-se commented Oct 31, 2021

That would avoid both essentially checking twice and potentially "missing" the result in some sense since it combines the check with actually getting the results

.join() doesn't do any checks that .is_running() does (it doesn't even check the refcount), so there's no duplicate check that can be avoided. And there's no way to "miss" the result, since the only way to get the result is to .join() which consumes the (only, non-clonable) JoinHandle.

I could add a try_join() that just does if !is_running() { join() } for convenience, but that hides the fact that it might still block for a brief moment while the thread is still running the implementation's cleanup code. Not sure how important that is.

It can still be useful to have .is_running() too, to be able to check if the works is done without having to use the result directly.

@m-ou-se
Copy link
Member Author

m-ou-se commented Oct 31, 2021

The signature of try_join() would also be an interesting question, since it has to consume Self when it joins, but leave it alone when it doesn't join.

@the8472
Copy link
Member

the8472 commented Oct 31, 2021

I could add a try_join() that just does if !is_running() { join() } for convenience, but that hides the fact that it might still block for a brief moment while the thread is still running the implementation's cleanup code. Not sure how important that is.

Wouldn't a Future-returning join be more useful then which can be polled for the Result (instead of polling is_running) without blocking on the thread cleanup?

@m-ou-se
Copy link
Member Author

m-ou-se commented Nov 1, 2021

Wouldn't a Future-returning join be more useful then which can be polled for the Result (instead of polling is_running)

Then as a user I'd need to provide a waker/context to be able to poll the thread.

without blocking on the thread cleanup?

You're referring to the code that runs on the thread after its main function returns? There's no portable way to check if a thread is really 'done'*. E.g. pthread doesn't provide anything for that. The only way would be to detach the thread and never join it at all.

(*For various definitions of 'done'.)

@Mark-Simulacrum
Copy link
Member

Hm. OK. I think we could do something like a try_take with basically https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.get_mut, which would let us try_get_result or something. I think this implementation is reasonable enough for now, and we can consider alternatives as part of stabilization; it's not clear to me that there's anything too much better given the limitations of the underlying interfaces. It's definitely the case that we expect a very short wait after is_running is false in general -- it should just be the system cleanup for the most part. We could in theory pull out the result value of the thread within the is_running if strong_count = 1, but the user (or we) would still need to call the inner join() in order to not leak the thread resources, so it's not trivially done I suspect. Maybe something to consider in the future.

r=me with the tracking issue filled in

@m-ou-se
Copy link
Member Author

m-ou-se commented Nov 1, 2021

@bors r=Mark-Simulacrum

@bors
Copy link
Contributor

bors commented Nov 1, 2021

📌 Commit 978ebd9 has been approved by Mark-Simulacrum

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 1, 2021
@the8472
Copy link
Member

the8472 commented Nov 1, 2021

We could in theory pull out the result value of the thread within the is_running if strong_count = 1, but the user (or we) would still need to call the inner join() in order to not leak the thread resources

Wouldn't detaching the thread after pulling out the result work on platforms that don't have a non-blocking join?

matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Nov 1, 2021
…imulacrum

Add JoinHandle::is_running.

This adds:
```rust
impl<T> JoinHandle<T> {
    /// Checks if the the associated thread is still running its main function.
    ///
    /// This might return `false` for a brief moment after the thread's main
    /// function has returned, but before the thread itself has stopped running.
    pub fn is_running(&self) -> bool;
}
```
The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information.

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Nov 1, 2021
…imulacrum

Add JoinHandle::is_running.

This adds:
```rust
impl<T> JoinHandle<T> {
    /// Checks if the the associated thread is still running its main function.
    ///
    /// This might return `false` for a brief moment after the thread's main
    /// function has returned, but before the thread itself has stopped running.
    pub fn is_running(&self) -> bool;
}
```
The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information.

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Nov 2, 2021
…imulacrum

Add JoinHandle::is_running.

This adds:
```rust
impl<T> JoinHandle<T> {
    /// Checks if the the associated thread is still running its main function.
    ///
    /// This might return `false` for a brief moment after the thread's main
    /// function has returned, but before the thread itself has stopped running.
    pub fn is_running(&self) -> bool;
}
```
The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information.

This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.
@bors
Copy link
Contributor

bors commented Nov 2, 2021

⌛ Testing commit 978ebd9 with merge 6384dca...

@bors
Copy link
Contributor

bors commented Nov 2, 2021

☀️ Test successful - checks-actions
Approved by: Mark-Simulacrum
Pushing 6384dca to master...

@bors bors added the merged-by-bors This PR was explicitly merged by bors. label Nov 2, 2021
@bors bors merged commit 6384dca into rust-lang:master Nov 2, 2021
@rustbot rustbot added this to the 1.58.0 milestone Nov 2, 2021
@rust-timer
Copy link
Collaborator

Finished benchmarking commit (6384dca): comparison url.

Summary: This benchmark run did not return any relevant changes.

If you disagree with this performance assessment, please file an issue in rust-lang/rustc-perf.

@rustbot label: -perf-regression

@m-ou-se m-ou-se deleted the thread-is-running branch November 4, 2021 10:59
// Joining the thread should not block for a significant time now.
let join_time = Instant::now();
assert_eq!(t.join().unwrap(), 1234);
assert!(join_time.elapsed() < Duration::from_secs(2));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this relaible? Maybe Duration::from_secs(2 + 1.0) better?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would three seconds be more reliable than two?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-runtime Area: std's runtime and "pre-main" init for handling backtraces, unwinds, stack overflows merged-by-bors This PR was explicitly merged by bors. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

8 participants