thread.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. use std::fmt::{self, Debug};
  3. use std::thread::{self, ThreadId};
  4. /// ThreadBound is a Sync-maker and Send-maker that allows accessing a value
  5. /// of type T only from the original thread on which the ThreadBound was
  6. /// constructed.
  7. pub(crate) struct ThreadBound<T> {
  8. value: T,
  9. thread_id: ThreadId,
  10. }
  11. unsafe impl<T> Sync for ThreadBound<T> {}
  12. // Send bound requires Copy, as otherwise Drop could run in the wrong place.
  13. //
  14. // Today Copy and Drop are mutually exclusive so `T: Copy` implies `T: !Drop`.
  15. // This impl needs to be revisited if that restriction is relaxed in the future.
  16. unsafe impl<T: Copy> Send for ThreadBound<T> {}
  17. impl<T> ThreadBound<T> {
  18. pub(crate) fn new(value: T) -> Self {
  19. ThreadBound {
  20. value,
  21. thread_id: thread::current().id(),
  22. }
  23. }
  24. pub(crate) fn get(&self) -> Option<&T> {
  25. if thread::current().id() == self.thread_id {
  26. Some(&self.value)
  27. } else {
  28. None
  29. }
  30. }
  31. }
  32. impl<T: Debug> Debug for ThreadBound<T> {
  33. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  34. match self.get() {
  35. Some(value) => Debug::fmt(value, formatter),
  36. None => formatter.write_str("unknown"),
  37. }
  38. }
  39. }
  40. // Copy the bytes of T, even if the currently running thread is the "wrong"
  41. // thread. This is fine as long as the original thread is not simultaneously
  42. // mutating this value via interior mutability, which would be a data race.
  43. //
  44. // Currently `T: Copy` is sufficient to guarantee that T contains no interior
  45. // mutability, because _all_ interior mutability in Rust is built on
  46. // std::cell::UnsafeCell, which has no Copy impl. This impl needs to be
  47. // revisited if that restriction is relaxed in the future.
  48. impl<T: Copy> Copy for ThreadBound<T> {}
  49. impl<T: Copy> Clone for ThreadBound<T> {
  50. fn clone(&self) -> Self {
  51. *self
  52. }
  53. }