Skip to content

Commit

Permalink
Use gettid for thread id on unix
Browse files Browse the repository at this point in the history
  • Loading branch information
Felix Obenhuber committed Jul 20, 2023
1 parent 76cb48d commit c94538d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
20 changes: 18 additions & 2 deletions examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::thread;

use log::*;

fn main() {
Expand All @@ -15,8 +17,22 @@ fn main() {
// Use a custom target string that is used as tag
info!(target: "custom", "hello custom target");

// Invoke a log from a submodule
hello_again::hello();
for _ in 0..3 {
thread::spawn(|| {
trace!("hello");
info!("helloHello");
warn!("hellohello");
error!("HELLOHELLO");

// Use a custom target string that is used as tag
info!(target: "custom", "hello custom target");

// Invoke a log from a submodule
hello_again::hello();
})
.join()
.expect("failed to join thread");
}
}

mod hello_again {
Expand Down
23 changes: 16 additions & 7 deletions src/thread.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
#[cfg(unix)]
#[cfg(any(target_os = "linux", target_os = "android"))]
#[inline]
pub fn id() -> usize {
pub fn id() -> i32 {
#[allow(clippy::unnecessary_cast)]
unsafe {
libc::pthread_self() as usize
libc::gettid() as i32
}
}

#[cfg(target_os = "macos")]
#[inline]
pub fn id() -> i32 {
#[allow(clippy::unnecessary_cast)]
unsafe {
libc::pthread_self() as i32
}
}

#[cfg(windows)]
#[inline]
pub fn id() -> usize {
unsafe { winapi::um::processthreadsapi::GetCurrentThreadId() as usize }
pub fn id() -> i32 {
unsafe { winapi::um::processthreadsapi::GetCurrentThreadId() as i32 }
}

#[cfg(target_os = "redox")]
#[inline]
pub fn id() -> usize {
pub fn id() -> i32 {
// Each thread has a separate pid on Redox.
syscall::getpid().unwrap()
syscall::getpid().unwrap() as i32
}

0 comments on commit c94538d

Please sign in to comment.