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

Optimize is_main_thread by using a libc call #616

Merged
merged 1 commit into from
May 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions framework-crates/objc2-foundation/src/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,37 @@ pub fn is_multi_threaded() -> bool {

/// Whether the current thread is the main thread.
#[cfg(feature = "NSThread")]
#[inline]
pub fn is_main_thread() -> bool {
Copy link
Owner

Choose a reason for hiding this comment

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

Nit: Could you #[inline] this and the imp functions, so that they can be inlined even without LTO?

Copy link
Owner

Choose a reason for hiding this comment

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

And also, I'm doing merge commits in this repo, so if you could squash, that'd be nice!

NSThread::isMainThread_class()
#[cfg(not(feature = "gnustep-1-7"))]
#[inline(always)]
fn imp() -> bool {
// Normally you would use NSThread::isMainThread, but that function uses pthread_main_np under
// the hood. Benchmarks have shown that calling it directly is up to four times faster. So, we
// just use that instead.

#[cfg(feature = "libc")]
use libc::pthread_main_np;

#[link(name = "c", kind = "dylib")]
#[cfg(not(feature = "libc"))]
extern "C" {
// Avoid a dependency on `libc` if possible
fn pthread_main_np() -> std::os::raw::c_int;
}

// SAFETY: Does not affect thread safety if we're running in an actual macOS environment.
unsafe { pthread_main_np() != 0 }
}

#[cfg(feature = "gnustep-1-7")]
#[inline(always)]
fn imp() -> bool {
// Fall back to isMainThread on GNUStep, as pthread_main_np is not always available.
NSThread::isMainThread_class()
}

imp()
}

#[allow(unused)]
Expand Down Expand Up @@ -181,7 +210,7 @@ impl MainThreadMarker {
#[cfg(feature = "NSThread")]
#[inline]
pub fn new() -> Option<Self> {
if NSThread::isMainThread_class() {
if is_main_thread() {
// SAFETY: We just checked that we are running on the main thread.
Some(unsafe { Self::new_unchecked() })
} else {
Expand Down