Skip to content

Commit f880d02

Browse files
committed
Add a virtual wrapper for &Latch
1 parent a46e1f8 commit f880d02

File tree

3 files changed

+36
-8
lines changed

3 files changed

+36
-8
lines changed

rayon-core/src/broadcast/mod.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::job::{ArcJob, StackJob};
2+
use crate::latch::LatchRef;
23
use crate::registry::{Registry, WorkerThread};
34
use crate::scope::ScopeLatch;
45
use std::fmt;
@@ -107,7 +108,9 @@ where
107108
let n_threads = registry.num_threads();
108109
let current_thread = WorkerThread::current().as_ref();
109110
let latch = ScopeLatch::with_count(n_threads, current_thread);
110-
let jobs: Vec<_> = (0..n_threads).map(|_| StackJob::new(&f, &latch)).collect();
111+
let jobs: Vec<_> = (0..n_threads)
112+
.map(|_| StackJob::new(&f, LatchRef::new(&latch)))
113+
.collect();
111114
let job_refs = jobs.iter().map(|job| job.as_job_ref());
112115

113116
registry.inject_broadcast(job_refs);

rayon-core/src/latch.rs

+30-5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::marker::PhantomData;
2+
use std::ops::Deref;
13
use std::sync::atomic::{AtomicUsize, Ordering};
24
use std::sync::{Arc, Condvar, Mutex};
35
use std::usize;
@@ -378,12 +380,35 @@ impl Latch for CountLockLatch {
378380
}
379381
}
380382

381-
impl<'a, L> Latch for &'a L
382-
where
383-
L: Latch,
384-
{
383+
/// `&L` without any implication of `dereferenceable` for `Latch::set`
384+
pub(super) struct LatchRef<'a, L> {
385+
inner: *const L,
386+
marker: PhantomData<&'a L>,
387+
}
388+
389+
impl<L> LatchRef<'_, L> {
390+
pub(super) fn new(inner: &L) -> LatchRef<'_, L> {
391+
LatchRef {
392+
inner,
393+
marker: PhantomData,
394+
}
395+
}
396+
}
397+
398+
unsafe impl<L: Sync> Sync for LatchRef<'_, L> {}
399+
400+
impl<L> Deref for LatchRef<'_, L> {
401+
type Target = L;
402+
403+
fn deref(&self) -> &L {
404+
// SAFETY: if we have &self, the inner latch is still alive
405+
unsafe { &*self.inner }
406+
}
407+
}
408+
409+
impl<L: Latch> Latch for LatchRef<'_, L> {
385410
#[inline]
386411
unsafe fn set(this: *const Self) {
387-
L::set(&**this);
412+
L::set((*this).inner);
388413
}
389414
}

rayon-core/src/registry.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::job::{JobFifo, JobRef, StackJob};
2-
use crate::latch::{AsCoreLatch, CoreLatch, CountLatch, Latch, LockLatch, SpinLatch};
2+
use crate::latch::{AsCoreLatch, CoreLatch, CountLatch, Latch, LatchRef, LockLatch, SpinLatch};
33
use crate::log::Event::*;
44
use crate::log::Logger;
55
use crate::sleep::Sleep;
@@ -505,7 +505,7 @@ impl Registry {
505505
assert!(injected && !worker_thread.is_null());
506506
op(&*worker_thread, true)
507507
},
508-
l,
508+
LatchRef::new(l),
509509
);
510510
self.inject(&[job.as_job_ref()]);
511511
job.latch.wait_and_reset(); // Make sure we can use the same latch again next time.

0 commit comments

Comments
 (0)