]> git.proxmox.com Git - rustc.git/blob - vendor/crossbeam-epoch-0.3.1/src/guard.rs
New upstream version 1.39.0+dfsg1
[rustc.git] / vendor / crossbeam-epoch-0.3.1 / src / guard.rs
1 use core::ptr;
2 use core::mem;
3
4 use garbage::Garbage;
5 use internal::Local;
6
7 /// A guard that keeps the current thread pinned.
8 ///
9 /// # Pinning
10 ///
11 /// The current thread is pinned by calling [`pin`], which returns a new guard:
12 ///
13 /// ```
14 /// use crossbeam_epoch as epoch;
15 ///
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();
19 /// ```
20 ///
21 /// When a guard gets dropped, the current thread is automatically unpinned.
22 ///
23 /// # Pointers on the stack
24 ///
25 /// Having a guard allows us to create pointers on the stack to heap-allocated objects.
26 /// For example:
27 ///
28 /// ```
29 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
30 /// use std::sync::atomic::Ordering::SeqCst;
31 ///
32 /// // Create a heap-allocated number.
33 /// let a = Atomic::new(777);
34 ///
35 /// // Pin the current thread.
36 /// let guard = &epoch::pin();
37 ///
38 /// // Load the heap-allocated object and create pointer `p` on the stack.
39 /// let p = a.load(SeqCst, guard);
40 ///
41 /// // Dereference the pointer and print the value:
42 /// if let Some(num) = unsafe { p.as_ref() } {
43 /// println!("The number is {}.", num);
44 /// }
45 /// ```
46 ///
47 /// # Multiple guards
48 ///
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
51 /// one is dropped:
52 ///
53 /// ```
54 /// use crossbeam_epoch as epoch;
55 ///
56 /// let guard1 = epoch::pin();
57 /// let guard2 = epoch::pin();
58 /// assert!(epoch::is_pinned());
59 /// drop(guard1);
60 /// assert!(epoch::is_pinned());
61 /// drop(guard2);
62 /// assert!(!epoch::is_pinned());
63 /// ```
64 ///
65 /// The same can be achieved by cloning guards:
66 ///
67 /// ```
68 /// use crossbeam_epoch as epoch;
69 ///
70 /// let guard1 = epoch::pin();
71 /// let guard2 = guard1.clone();
72 /// ```
73 ///
74 /// [`pin`]: fn.pin.html
75 pub struct Guard {
76 local: *const Local,
77 }
78
79 impl Guard {
80 /// Creates a new guard from a pointer to `Local`.
81 ///
82 /// # Safety
83 ///
84 /// The `local` should be a valid pointer created by `Local::register()`.
85 #[doc(hidden)]
86 pub unsafe fn new(local: *const Local) -> Guard {
87 Guard { local: local }
88 }
89
90 /// Accesses the internal pointer to `Local`.
91 #[doc(hidden)]
92 pub unsafe fn get_local(&self) -> *const Local {
93 self.local
94 }
95
96 /// Stores a function so that it can be executed at some point after all currently pinned
97 /// threads get unpinned.
98 ///
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.
103 ///
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.
107 ///
108 /// If this method is called from an [`unprotected`] guard, the function will simply be
109 /// executed immediately.
110 ///
111 /// # Safety
112 ///
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
115 /// borrows.
116 ///
117 /// ```
118 /// use crossbeam_epoch as epoch;
119 ///
120 /// let guard = &epoch::pin();
121 /// let message = "Hello!";
122 /// unsafe {
123 /// // ALWAYS use `move` when sending a closure into `defef`.
124 /// guard.defer(move || {
125 /// println!("{}", message);
126 /// });
127 /// }
128 /// ```
129 ///
130 /// Apart from that, keep in mind that another thread may execute `f`, so anything accessed
131 /// by the closure must be `Send`.
132 ///
133 /// # Examples
134 ///
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.
140 ///
141 /// ```rust
142 /// use crossbeam_epoch::{self as epoch, Atomic, Owned};
143 /// use std::sync::atomic::Ordering::SeqCst;
144 ///
145 /// let a = Atomic::new("foo");
146 ///
147 /// // Now suppose that `a` is shared among multiple threads and concurrently
148 /// // accessed and modified...
149 ///
150 /// // Pin the current thread.
151 /// let guard = &epoch::pin();
152 ///
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);
155 ///
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.
159 /// unsafe {
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());
166 /// });
167 /// }
168 /// }
169 /// ```
170 ///
171 /// [`unprotected`]: fn.unprotected.html
172 pub unsafe fn defer<F, R>(&self, f: F)
173 where
174 F: FnOnce() -> R,
175 {
176 let garbage = Garbage::new(|| drop(f()));
177
178 if let Some(local) = self.local.as_ref() {
179 local.defer(garbage, self);
180 }
181 }
182
183 /// Clears up the thread-local cache of deferred functions by executing them or moving into the
184 /// global cache.
185 ///
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.
189 ///
190 /// If this method is called from an [`unprotected`] guard, it is a no-op (nothing happens).
191 ///
192 /// # Examples
193 ///
194 /// ```
195 /// use crossbeam_epoch as epoch;
196 ///
197 /// let guard = &epoch::pin();
198 /// unsafe {
199 /// guard.defer(move || {
200 /// println!("This better be printed as soon as possible!");
201 /// });
202 /// }
203 /// guard.flush();
204 /// ```
205 ///
206 /// [`unprotected`]: fn.unprotected.html
207 pub fn flush(&self) {
208 if let Some(local) = unsafe { self.local.as_ref() } {
209 local.flush(self);
210 }
211 }
212
213 /// Unpins and then immediately re-pins the thread.
214 ///
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.
219 ///
220 /// If this method is called from an [`unprotected`] guard, then the call will be just no-op.
221 ///
222 /// # Examples
223 ///
224 /// ```
225 /// use crossbeam_epoch::{self as epoch, Atomic};
226 /// use std::sync::atomic::Ordering::SeqCst;
227 /// use std::thread;
228 /// use std::time::Duration;
229 ///
230 /// let a = Atomic::new(777);
231 /// let mut guard = epoch::pin();
232 /// {
233 /// let p = a.load(SeqCst, &guard);
234 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
235 /// }
236 /// guard.repin();
237 /// {
238 /// let p = a.load(SeqCst, &guard);
239 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
240 /// }
241 /// ```
242 ///
243 /// [`unprotected`]: fn.unprotected.html
244 pub fn repin(&mut self) {
245 if let Some(local) = unsafe { self.local.as_ref() } {
246 local.repin();
247 }
248 }
249
250 /// Temporarily unpins the thread, executes the given function and then re-pins the thread.
251 ///
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
255 /// current thread.
256 ///
257 /// If this method is called from an [`unprotected`] guard, then the passed function is called
258 /// directly without unpinning the thread.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// use crossbeam_epoch::{self as epoch, Atomic};
264 /// use std::sync::atomic::Ordering::SeqCst;
265 /// use std::thread;
266 /// use std::time::Duration;
267 ///
268 /// let a = Atomic::new(777);
269 /// let mut guard = epoch::pin();
270 /// {
271 /// let p = a.load(SeqCst, &guard);
272 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
273 /// }
274 /// guard.repin_after(|| thread::sleep(Duration::from_millis(50)));
275 /// {
276 /// let p = a.load(SeqCst, &guard);
277 /// assert_eq!(unsafe { p.as_ref() }, Some(&777));
278 /// }
279 /// ```
280 ///
281 /// [`unprotected`]: fn.unprotected.html
282 pub fn repin_after<F, R>(&mut self, f: F) -> R
283 where
284 F: FnOnce() -> R,
285 {
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();
290 local.unpin();
291 }
292
293 // Ensure the Guard is re-pinned even if the function panics
294 defer! {
295 if let Some(local) = unsafe { self.local.as_ref() } {
296 mem::forget(local.pin());
297 local.release_handle();
298 }
299 }
300
301 f()
302 }
303 }
304
305 impl Drop for Guard {
306 #[inline]
307 fn drop(&mut self) {
308 if let Some(local) = unsafe { self.local.as_ref() } {
309 local.unpin();
310 }
311 }
312 }
313
314 impl Clone for Guard {
315 #[inline]
316 fn clone(&self) -> Guard {
317 match unsafe { self.local.as_ref() } {
318 None => Guard { local: ptr::null() },
319 Some(local) => local.pin(),
320 }
321 }
322 }
323
324 /// Returns a reference to a dummy guard that allows unprotected access to [`Atomic`]s.
325 ///
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.
328 ///
329 /// Note that calling [`defer`] with a dummy guard will not defer the function - it will just
330 /// execute the function immediately.
331 ///
332 /// If necessary, it's possible to create more dummy guards by cloning: `unprotected().clone()`.
333 ///
334 /// # Safety
335 ///
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.
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// use crossbeam_epoch::{self as epoch, Atomic};
343 /// use std::sync::atomic::Ordering::Relaxed;
344 ///
345 /// let a = Atomic::new(7);
346 ///
347 /// unsafe {
348 /// // Load `a` without pinning the current thread.
349 /// a.load(Relaxed, epoch::unprotected());
350 ///
351 /// // It's possible to create more dummy guards by calling `clone()`.
352 /// let dummy = &epoch::unprotected().clone();
353 ///
354 /// dummy.defer(move || {
355 /// println!("This gets executed immediately.");
356 /// });
357 ///
358 /// // Dropping `dummy` doesn't affect the current thread - it's just a noop.
359 /// }
360 /// ```
361 ///
362 /// The most common use of this function is when constructing or destructing a data structure.
363 ///
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.
366 ///
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`
369 /// is very helpful.
370 ///
371 /// ```
372 /// use crossbeam_epoch::{self as epoch, Atomic};
373 /// use std::ptr;
374 /// use std::sync::atomic::Ordering::Relaxed;
375 ///
376 /// struct Stack {
377 /// head: epoch::Atomic<Node>,
378 /// }
379 ///
380 /// struct Node {
381 /// data: u32,
382 /// next: epoch::Atomic<Node>,
383 /// }
384 ///
385 /// impl Drop for Stack {
386 /// fn drop(&mut self) {
387 /// unsafe {
388 /// // Unprotected load.
389 /// let mut node = self.head.load(Relaxed, epoch::unprotected());
390 ///
391 /// while let Some(n) = node.as_ref() {
392 /// // Unprotected load.
393 /// let next = n.next.load(Relaxed, epoch::unprotected());
394 ///
395 /// // Take ownership of the node, then drop it.
396 /// drop(node.into_owned());
397 ///
398 /// node = next;
399 /// }
400 /// }
401 /// }
402 /// }
403 /// ```
404 ///
405 /// [`Atomic`]: struct.Atomic.html
406 /// [`defer`]: struct.Guard.html#method.defer
407 #[inline]
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)
417 }