7 /// A guard that keeps the current thread pinned.
11 /// The current thread is pinned by calling [`pin`], which returns a new guard:
14 /// use crossbeam_epoch as epoch;
16 /// // It is often convenient to prefix a call to `pin` with a `&` in order to create a reference.
17 /// // This is not really necessary, but makes passing references to the guard a bit easier.
18 /// let guard = &epoch::pin();
21 /// When a guard gets dropped, the current thread is automatically unpinned.
23 /// # Pointers on the stack
25 /// Having a guard allows us to create pointers on the stack to heap-allocated objects.
29 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
30 /// use std::sync::atomic::Ordering::SeqCst;
32 /// // Create a heap-allocated number.
33 /// let a = Atomic::new(777);
35 /// // Pin the current thread.
36 /// let guard = &epoch::pin();
38 /// // Load the heap-allocated object and create pointer `p` on the stack.
39 /// let p = a.load(SeqCst, guard);
41 /// // Dereference the pointer and print the value:
42 /// if let Some(num) = unsafe { p.as_ref() } {
43 /// println!("The number is {}.", num);
49 /// Pinning is reentrant and it is perfectly legal to create multiple guards. In that case, the
50 /// thread will actually be pinned only when the first guard is created and unpinned when the last
54 /// use crossbeam_epoch as epoch;
56 /// let guard1 = epoch::pin();
57 /// let guard2 = epoch::pin();
58 /// assert!(epoch::is_pinned());
60 /// assert!(epoch::is_pinned());
62 /// assert!(!epoch::is_pinned());
65 /// The same can be achieved by cloning guards:
68 /// use crossbeam_epoch as epoch;
70 /// let guard1 = epoch::pin();
71 /// let guard2 = guard1.clone();
74 /// [`pin`]: fn.pin.html
80 /// Creates a new guard from a pointer to `Local`.
84 /// The `local` should be a valid pointer created by `Local::register()`.
86 pub unsafe fn new(local
: *const Local
) -> Guard
{
87 Guard { local: local }
90 /// Accesses the internal pointer to `Local`.
92 pub unsafe fn get_local(&self) -> *const Local
{
96 /// Stores a function so that it can be executed at some point after all currently pinned
97 /// threads get unpinned.
99 /// This method first stores `f` into the thread-local (or handle-local) cache. If this cache
100 /// becomes full, some functions are moved into the global cache. At the same time, some
101 /// functions from both local and global caches may get executed in order to incrementally
102 /// clean up the caches as they fill up.
104 /// There is no guarantee when exactly `f` will be executed. The only guarantee is that won't
105 /// until all currently pinned threads get unpinned. In theory, `f` might never be deallocated,
106 /// but the epoch-based garbage collection will make an effort to execute it reasonably soon.
108 /// If this method is called from an [`unprotected`] guard, the function will simply be
109 /// executed immediately.
113 /// The given function must not hold reference onto the stack. It is highly recommended that
114 /// the passed function is **always** marked with `move` in order to prevent accidental
118 /// use crossbeam_epoch as epoch;
120 /// let guard = &epoch::pin();
121 /// let message = "Hello!";
123 /// // ALWAYS use `move` when sending a closure into `defef`.
124 /// guard.defer(move || {
125 /// println!("{}", message);
130 /// Apart from that, keep in mind that another thread may execute `f`, so anything accessed
131 /// by the closure must be `Send`.
135 /// When a heap-allocated object in a data structure becomes unreachable, it has to be
136 /// deallocated. However, the current thread and other threads may be still holding references
137 /// on the stack to that same object. Therefore it cannot be deallocated before those
138 /// references get dropped. This method can defer deallocation until all those threads get
139 /// unpinned and consequently drop all their references on the stack.
142 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
143 /// use std::sync::atomic::Ordering::SeqCst;
145 /// let a = Atomic::new("foo");
147 /// // Now suppose that `a` is shared among multiple threads and concurrently
148 /// // accessed and modified...
150 /// // Pin the current thread.
151 /// let guard = &epoch::pin();
153 /// // Steal the object currently stored in `a` and swap it with another one.
154 /// let p = a.swap(Owned::new("bar").into_shared(guard), SeqCst, guard);
156 /// if !p.is_null() {
157 /// // The object `p` is pointing to is now unreachable.
158 /// // Defer its deallocation until all currently pinned threads get unpinned.
160 /// // ALWAYS use `move` when sending a closure into `defer`.
161 /// guard.defer(move || {
162 /// println!("{} is now being deallocated.", p.deref());
163 /// // Now we have unique access to the object pointed to by `p` and can turn it
164 /// // into an `Owned`. Dropping the `Owned` will deallocate the object.
165 /// drop(p.into_owned());
171 /// [`unprotected`]: fn.unprotected.html
172 pub unsafe fn defer
<F
, R
>(&self, f
: F
)
176 let garbage
= Garbage
::new(|| drop(f()));
178 if let Some(local
) = self.local
.as_ref() {
179 local
.defer(garbage
, self);
183 /// Clears up the thread-local cache of deferred functions by executing them or moving into the
186 /// Call this method after deferring execution of a function if you want to get it executed as
187 /// soon as possible. Flushing will make sure it is residing in in the global cache, so that
188 /// any thread has a chance of taking the function and executing it.
190 /// If this method is called from an [`unprotected`] guard, it is a no-op (nothing happens).
195 /// use crossbeam_epoch as epoch;
197 /// let guard = &epoch::pin();
199 /// guard.defer(move || {
200 /// println!("This better be printed as soon as possible!");
206 /// [`unprotected`]: fn.unprotected.html
207 pub fn flush(&self) {
208 if let Some(local
) = unsafe { self.local.as_ref() }
{
213 /// Unpins and then immediately re-pins the thread.
215 /// This method is useful when you don't want delay the advancement of the global epoch by
216 /// holding an old epoch. For safety, you should not maintain any guard-based reference across
217 /// the call (the latter is enforced by `&mut self`). The thread will only be repinned if this
218 /// is the only active guard for the current thread.
220 /// If this method is called from an [`unprotected`] guard, then the call will be just no-op.
225 /// use crossbeam_epoch::{self as epoch, Atomic};
226 /// use std::sync::atomic::Ordering::SeqCst;
228 /// use std::time::Duration;
230 /// let a = Atomic::new(777);
231 /// let mut guard = epoch::pin();
233 /// let p = a.load(SeqCst, &guard);
234 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
238 /// let p = a.load(SeqCst, &guard);
239 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
243 /// [`unprotected`]: fn.unprotected.html
244 pub fn repin(&mut self) {
245 if let Some(local
) = unsafe { self.local.as_ref() }
{
250 /// Temporarily unpins the thread, executes the given function and then re-pins the thread.
252 /// This method is useful when you need to perform a long-running operation (e.g. sleeping)
253 /// and don't need to maintain any guard-based reference across the call (the latter is enforced
254 /// by `&mut self`). The thread will only be unpinned if this is the only active guard for the
257 /// If this method is called from an [`unprotected`] guard, then the passed function is called
258 /// directly without unpinning the thread.
263 /// use crossbeam_epoch::{self as epoch, Atomic};
264 /// use std::sync::atomic::Ordering::SeqCst;
266 /// use std::time::Duration;
268 /// let a = Atomic::new(777);
269 /// let mut guard = epoch::pin();
271 /// let p = a.load(SeqCst, &guard);
272 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
274 /// guard.repin_after(|| thread::sleep(Duration::from_millis(50)));
276 /// let p = a.load(SeqCst, &guard);
277 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
281 /// [`unprotected`]: fn.unprotected.html
282 pub fn repin_after
<F
, R
>(&mut self, f
: F
) -> R
286 if let Some(local
) = unsafe { self.local.as_ref() }
{
287 // We need to acquire a handle here to ensure the Local doesn't
288 // disappear from under us.
289 local
.acquire_handle();
293 // Ensure the Guard is re-pinned even if the function panics
295 if let Some(local
) = unsafe { self.local.as_ref() }
{
296 mem
::forget(local
.pin());
297 local
.release_handle();
305 impl Drop
for Guard
{
308 if let Some(local
) = unsafe { self.local.as_ref() }
{
314 impl Clone
for Guard
{
316 fn clone(&self) -> Guard
{
317 match unsafe { self.local.as_ref() }
{
318 None
=> Guard { local: ptr::null() }
,
319 Some(local
) => local
.pin(),
324 /// Returns a reference to a dummy guard that allows unprotected access to [`Atomic`]s.
326 /// This guard should be used in special occasions only. Note that it doesn't actually keep any
327 /// thread pinned - it's just a fake guard that allows loading from [`Atomic`]s unsafely.
329 /// Note that calling [`defer`] with a dummy guard will not defer the function - it will just
330 /// execute the function immediately.
332 /// If necessary, it's possible to create more dummy guards by cloning: `unprotected().clone()`.
336 /// Loading and dereferencing data from an [`Atomic`] using this guard is safe only if the
337 /// [`Atomic`] is not being concurrently modified by other threads.
342 /// use crossbeam_epoch::{self as epoch, Atomic};
343 /// use std::sync::atomic::Ordering::Relaxed;
345 /// let a = Atomic::new(7);
348 /// // Load `a` without pinning the current thread.
349 /// a.load(Relaxed, epoch::unprotected());
351 /// // It's possible to create more dummy guards by calling `clone()`.
352 /// let dummy = &epoch::unprotected().clone();
354 /// dummy.defer(move || {
355 /// println!("This gets executed immediately.");
358 /// // Dropping `dummy` doesn't affect the current thread - it's just a noop.
362 /// The most common use of this function is when constructing or destructing a data structure.
364 /// For example, we can use a dummy guard in the destructor of a Treiber stack because at that
365 /// point no other thread could concurrently modify the [`Atomic`]s we are accessing.
367 /// If we were to actually pin the current thread during destruction, that would just unnecessarily
368 /// delay garbage collection and incur some performance cost, so in cases like these `unprotected`
372 /// use crossbeam_epoch::{self as epoch, Atomic};
374 /// use std::sync::atomic::Ordering::Relaxed;
377 /// head: epoch::Atomic<Node>,
382 /// next: epoch::Atomic<Node>,
385 /// impl Drop for Stack {
386 /// fn drop(&mut self) {
388 /// // Unprotected load.
389 /// let mut node = self.head.load(Relaxed, epoch::unprotected());
391 /// while let Some(n) = node.as_ref() {
392 /// // Unprotected load.
393 /// let next = n.next.load(Relaxed, epoch::unprotected());
395 /// // Take ownership of the node, then drop it.
396 /// drop(node.into_owned());
405 /// [`Atomic`]: struct.Atomic.html
406 /// [`defer`]: struct.Guard.html#method.defer
408 pub unsafe fn unprotected() -> &'
static Guard
{
409 // HACK(stjepang): An unprotected guard is just a `Guard` with its field `local` set to null.
410 // Since this function returns a `'static` reference to a `Guard`, we must return a reference
411 // to a global guard. However, it's not possible to create a `static` `Guard` because it does
412 // not implement `Sync`. To get around the problem, we create a static `usize` initialized to
413 // zero and then transmute it into a `Guard`. This is safe because `usize` and `Guard`
414 // (consisting of a single pointer) have the same representation in memory.
415 static UNPROTECTED
: usize = 0;
416 &*(&UNPROTECTED
as *const _
as *const Guard
)