pal/unix/
pthread.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Pthread, a basic Linux pthread (pthread_t) wrapper to support send
5//! and sync on musl.
6
7use std::io;
8
9#[derive(Debug, Copy, Clone, PartialEq, Eq)]
10pub struct Pthread(libc::pthread_t);
11
12// SAFETY: pthread_t is an opaque handle and is safe to share/send between
13// threads. But it's a pointer type on musl so does not default to Send+Sync.
14unsafe impl Send for Pthread {}
15// SAFETY: see above comment.
16unsafe impl Sync for Pthread {}
17
18impl Pthread {
19    /// Gets a Pthread object initialized with the caller thread.
20    pub fn current() -> Self {
21        // SAFETY: calling C API as documented, with no special requirements.
22        Self(unsafe { libc::pthread_self() })
23    }
24
25    /// Sends a signal to Pthread's thread.
26    pub fn signal(&self, signal: i32) -> io::Result<()> {
27        // SAFETY: calling as documented, with no special requirements.
28        unsafe {
29            if libc::pthread_kill(self.0, signal) != 0 {
30                return Err(io::Error::last_os_error());
31            }
32        }
33        Ok(())
34    }
35}