Skip to content

Commit

Permalink
Use OnceLock in JobTokenServer::new
Browse files Browse the repository at this point in the history
Also impls `Send`, `Sync`, `RefUnwindSafe` and `UnwindSafed` when the `T`
meets the criterior.

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
  • Loading branch information
NobodyXu committed Apr 18, 2024
1 parent e9ce514 commit 4e9adfe
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 22 deletions.
31 changes: 11 additions & 20 deletions src/parallel/job_token.rs
@@ -1,6 +1,6 @@
use std::{marker::PhantomData, mem::MaybeUninit, sync::Once};
use std::marker::PhantomData;

use crate::Error;
use crate::{parallel::once_lock::OnceLock, Error};

pub(crate) struct JobToken(PhantomData<()>);

Expand Down Expand Up @@ -34,19 +34,13 @@ impl JobTokenServer {
/// that has to be static so that it will be shared by all cc
/// compilation.
fn new() -> &'static Self {
// TODO: Replace with a OnceLock once MSRV is 1.70
static INIT: Once = Once::new();
static mut JOBSERVER: MaybeUninit<JobTokenServer> = MaybeUninit::uninit();

unsafe {
INIT.call_once(|| {
let server = inherited_jobserver::JobServer::from_env()
.map(Self::Inherited)
.unwrap_or_else(|| Self::InProcess(inprocess_jobserver::JobServer::new()));
JOBSERVER.write(server);
});
JOBSERVER.assume_init_ref()
}
static JOBSERVER: OnceLock<JobTokenServer> = OnceLock::new();

JOBSERVER.get_or_init(|| {
unsafe { inherited_jobserver::JobServer::from_env() }
.map(Self::Inherited)
.unwrap_or_else(|| Self::InProcess(inprocess_jobserver::JobServer::new()))
})
}
}

Expand Down Expand Up @@ -76,12 +70,9 @@ impl ActiveJobTokenServer {
}

mod inherited_jobserver {
use super::JobToken;
use super::{JobToken, OnceLock};

use crate::{
parallel::{async_executor::YieldOnce, once_lock::OnceLock},
Error, ErrorKind,
};
use crate::{parallel::async_executor::YieldOnce, Error, ErrorKind};

use std::{
io, mem,
Expand Down
14 changes: 12 additions & 2 deletions src/parallel/once_lock.rs
Expand Up @@ -3,7 +3,12 @@
//! is initialised and MSRV is high enoguh to use it.

use std::{
cell::UnsafeCell, convert::Infallible, marker::PhantomData, mem::MaybeUninit, sync::Once,
cell::UnsafeCell,
convert::Infallible,
marker::PhantomData,
mem::MaybeUninit,
panic::{RefUnwindSafe, UnwindSafe},
sync::Once,
};

pub struct OnceLock<T> {
Expand Down Expand Up @@ -31,6 +36,12 @@ pub struct OnceLock<T> {
_marker: PhantomData<T>,
}

unsafe impl<T: Sync + Send> Sync for OnceLock<T> {}
unsafe impl<T: Send> Send for OnceLock<T> {}

impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}

impl<T> OnceLock<T> {
pub const fn new() -> OnceLock<T> {
OnceLock {
Expand All @@ -49,7 +60,6 @@ impl<T> OnceLock<T> {
}
}

#[allow(dead_code)]
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
Expand Down

0 comments on commit 4e9adfe

Please sign in to comment.